繁体   English   中英

numpy.savetxt 会覆盖原文件

[英]numpy.savetxt will overwrite the original file

例如,在下面的代码中,B 将覆盖 A 的数据,而 C 将覆盖 B 的数据。

np.savetxt

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")

我希望每次运行时将数据直接添加到下一行。

每次使用文件名都会新创建文件 - 通过提供文件句柄,您可以更好地控制文件生命周期:

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

库: np.savetxt

numpy.savetxt (fname, X, fmt='%.18e', delimiter='', newline='n', header='', footer='', comments='#', encoding=None)

fname:文件名或文件句柄

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM