How to save array iteratively to file in python?

2019-07-31 14:04发布

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!

2条回答
做自己的国王
2楼-- · 2019-07-31 14:30

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)

查看更多
Anthone
3楼-- · 2019-07-31 14:41

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

查看更多
登录 后发表回答