Rael
Rael

Reputation: 149

How to save array iteratively to file in python?

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

Answers (2)

AGN Gazer
AGN Gazer

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

sascha
sascha

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:

  • opening/closing the file in each iteration vs. keeping the file-handler open
  • using np.array_str / np.array_repr / np.array2string

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

Related Questions