例如,在下面的代码中,B将覆盖A的数据,而C将覆盖B的数据。
A = tf.constant([[1, 2, 3, 4]], tf.float32)
B = tf.constant([[10, 20, 30, 40]], tf.float32)
C = tf.constant([[11, 22, 33, 44]], tf.float32)
np.savetxt("foo.csv", A, fmt="%d")
np.savetxt("foo.csv", B, fmt="%d")
np.savetxt("foo.csv", C, fmt="%d")
我希望每次运行时将数据直接添加到下一行。
答案 0 :(得分:1)
使用文件名每次都会重新创建文件-通过提供 file handle 代替,您可以更好地控制文件的生命周期:
import numpy as np
A = np.array([[1, 2, 3, 4]], np.float32)
B = np.array([[10, 20, 30, 40]], np.float32)
C = np.array([[100, 200, 300, 400]], np.float32)
# open by creating new file and append to it
with open("foo.csv","w") as f:
np.savetxt(f, A, fmt="%d")
np.savetxt(f, B, fmt="%d")
# reopen and append to it
with open("foo.csv","a") as f:
np.savetxt(f, C, fmt="%d")
print(open("foo.csv").read())
输出:
1 2 3 4
10 20 30 40
100 200 300 400
Doku:np.savetxt
numpy.savetxt (fname,X,fmt ='%。18e',delimiter ='',newline ='n',header ='',footer ='',comments =' #',编码=无)
fname:文件名或 文件句柄