使用savetxt附加到文件

时间:2019-01-25 08:30:32

标签: python numpy

我正在尝试将数组b和c附加到file.txt。默认行为是覆盖,我找不到更改此内容的任何文档。

import numpy as np
a = np.array([1.2, 2.3, 4.5])
b = np.array([6.7, 8.9, 10.11])
c = np.array([12.13, 14.15, 16.17])

np.savetxt('file.txt', a, fmt='%1.3f', newline=", ")

谢谢

2 个答案:

答案 0 :(得分:2)

open()与'append'模式一起使用,并将流传递给savetxt方法:

with open("test.txt", "ab") as f:
    numpy.savetxt(f, a)

编辑:要添加新行,或执行以下操作:

with open("test.txt", "ab") as f:
    f.write(b"\n")
    numpy.savetxt(f, a)

答案 1 :(得分:1)

您应该以二进制模式打开文件

import numpy as np        
f=open('file.txt','a')
a = np.array([1.2, 2.3, 4.5])
b = np.array([6.7, 8.9, 10.11])
c = np.array([12.13, 14.15, 16.17])
np.savetxt(f, a, fmt='%1.3f', newline=", ")
f.write("\n")
np.savetxt(f, b, fmt='%1.3f', newline=", ")
f.write("\n")
np.savetxt(f, c, fmt='%1.3f', newline=", ")
f.write("\n")
f.close()