Reputation: 149
I want to do in a for loop something like this:
for i in range(n):
x = vector()
np.savetxt('t.txt', x, newline=" ")
but I want to save each array x as a new line in my file, but this doesn't happen with the code above, can anybody help? Thanks!
Upvotes: 1
Views: 1230
Reputation: 8378
Try this:
with open('t.txt', 'w') as f:
for i in range(n):
x = vector()
np.savetxt(f, x, newline=" ")
f.write('\n')
That is, pass an already open file handle to the numpy
's savetxt
function. This way it will not overwrite existing content. Also see Append element to binary file
Upvotes: 1
Reputation: 33522
I would go for something like (untested!):
for i in range(n):
x = vector()
with open("t.txt", "a") as f: # "a" for append!
f.write(np.array_str(x))
There are some decisions to make:
This of course is based on the assumption, that you can't wait to grab all data before writing all at once! (online-setting)
Upvotes: 0