【问题标题】:How to save array iteratively to file in python?如何迭代地将数组保存到python中的文件?
【发布时间】:2017-11-03 20:58:31
【问题描述】:

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

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

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

【问题讨论】:

  • newline="\n"怎么样,根据documentation是默认设置的?
  • "...但是上面的代码不会发生这种情况" 代码有什么问题? 会发生什么

标签: python file numpy


【解决方案1】:

试试这个:

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

【讨论】:

  • @Rael 如果它解决了您的问题,请考虑接受此答案。
【解决方案2】:

我会选择类似(未经测试!):

for i in range(n):
    x = vector()
    with open("t.txt", "a") as f:  # "a" for append!
        f.write(np.array_str(x))

需要做出一些决定:

  • 在每次迭代中打开/关闭文件与保持文件处理程序打开
  • 使用 np.array_str / np.array_repr / np.array2string

这当然是基于这样的假设,即您迫不及待地想在一次写入之前获取所有数据! (在线设置)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 2016-08-25
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 2016-06-21
    相关资源
    最近更新 更多