[英]Pythow write to txt file,my strings are overwritten by array
For example 例如
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')
But this is my new2.txt 但这是我的new2.txt
2900.0
2900.0
2900.0
2900.0
2900.0
I need first to write strings,then do some calculations and write down the array.How to do this? 我需要首先编写字符串,然后进行一些计算并写下数组。如何执行此操作?
Try this: 尝试这个:
h = 'vel.1d\n' + 'base.mod\n' # prepare file header
np.savetxt('new2.txt', a1, fmt = '%4.1f', header = h) # use header
If you use with open('new2.txt','w') as f:
, the file is closed after you leave the with
block, so savetxt
overwrites from the beginning. 如果将
with open('new2.txt','w') as f:
则在离开with
块后文件将关闭,因此savetxt
开始savetxt
被覆盖。 You could do: 您可以这样做:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.