Reputation: 21
For example, in the code below, B will overwrite A's data, and C will overwrite B's data.
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.
Upvotes: 1
Views: 4350
Reputation: 51643
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
Upvotes: 1