简体   繁体   中英

numpy.savetxt will overwrite the original file

For example, in the code below, B will overwrite A's data, and C will overwrite B's data.

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

I want the data to be added directly to the next line each time I run it.

Using a file name will create the file newly every time - you have more control over the files lifetime by providing a file handle instead:

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

Output:

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='# ', encoding=None)

fname: filename or file handle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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