1

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
  • How about newline="\n", which according to the documentation is set by default? Commented Nov 3, 2017 at 21:02
  • "...but this doesn't happen with the code above" What is the problem with the code? What does happen? Commented Nov 3, 2017 at 21:10

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Rael consider accepting this answer if it solved your issue.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.