Pythow写入txt文件,我的字符串被数组覆盖

时间:2016-04-26 17:08:22

标签: python io

例如

import numpy as np

with open('new2.txt','w') as f:
    f.write('vel.1d\n')
    f.write('base.mod\n')

a1=np.empty(5)
a1.fill(2900)   

np.savetxt('new2.txt',a1,fmt='%4.1f')

但这是我的new2.txt

2900.0
2900.0
2900.0
2900.0
2900.0

我首先需要编写字符串,然后进行一些计算并写下数组。如何做到这一点?

2 个答案:

答案 0 :(得分:1)

试试这个:

h = 'vel.1d\n' + 'base.mod\n' # prepare file header

np.savetxt('new2.txt', a1, fmt = '%4.1f', header = h) # use header

答案 1 :(得分:1)

如果您使用with open('new2.txt','w') as f:,则在您离开with块后该文件将被关闭,因此savetxt将从头开始覆盖。你可以这样做:

In [1]: import numpy as np

In [2]: a1=np.empty(5)

In [3]: a1.fill(2900)

In [4]: with open('new2.txt', 'w') as f:
    f.write('vel.1d\n')
    f.write('base.mod\n')
    np.savetxt(f,a1,fmt='%4.1f')