Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to file using savetxt

Tags:

python

numpy

I'm trying to append array b and c to file.txt. The default behavior is to overwrite and I cant find any documentation on changing this.

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

Thanks

like image 243
Q-bertsuit Avatar asked Jan 25 '19 08:01

Q-bertsuit


2 Answers

Use open() with the 'append' mode, and pass the stream to the savetxt method:

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

Edit: To add a new line, or whatever:

with open("test.txt", "ab") as f:
    f.write(b"\n")
    numpy.savetxt(f, a)
like image 78
olinox14 Avatar answered Sep 27 '22 23:09

olinox14


You should open the file in append mode

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()
like image 45
nacho Avatar answered Sep 28 '22 00:09

nacho