如何将数组迭代保存到python中的文件? [英] How to save array iteratively to file in python?
本文介绍了如何将数组迭代保存到python中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在for循环中执行以下操作:
I want to do in a for loop something like this:
for i in range(n):
x = vector()
np.savetxt('t.txt', x, newline=" ")
但是我想将每个数组x保存为文件中的新行,但是上面的代码并没有发生这种情况,有人可以帮忙吗?谢谢!
but I want to save each array x as a new line in my file, but this doesn't happen with the code above, can anybody help? Thanks!
推荐答案
尝试一下:
with open('t.txt', 'w') as f:
for i in range(n):
x = vector()
np.savetxt(f, x, newline=" ")
f.write('\n')
也就是说,将已经打开的文件句柄传递给numpy
的savetxt
函数.这样,它将不会覆盖现有内容.另请参见将元素附加到二进制文件
That is, pass an already open file handle to the numpy
's savetxt
function. This way it will not overwrite existing content. Also see Append element to binary file
这篇关于如何将数组迭代保存到python中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文