gpt4 book ai didi

python - 如何在Python中迭代地将数组保存到文件中?

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:46 26 4
gpt4 key购买 nike

我想在 for 循环中做这样的事情:

for i in range(n):
x = vector()
np.savetxt('t.txt', x, newline=" ")

但是我想将每个数组 x 保存为文件中的新行,但是上面的代码不会发生这种情况,有人可以帮忙吗?谢谢!

最佳答案

试试这个:

with open('t.txt', 'w') as f:
for i in range(n):
x = vector()
np.savetxt(f, x, newline=" ")
f.write('\n')

也就是说,将一个已经打开的文件句柄传递给 numpysavetxt 函数。这样它就不会覆盖现有内容。另请参阅Append element to binary file

关于python - 如何在Python中迭代地将数组保存到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47104306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com