0

I have a for loop in Python and in every iteration I would like to write the result to a new text file.

import numpy as np

n = 5
g = my_func()
for i in range(n):
    """ I wan to have test0.txt for i = 0
    test1.txt for i = 1 and so on ...
    """
    f = open('test.txt','ab')
    np.savetxt(f, g, fmt='%.0f', newline=" ")
f.close()

Is this possible?

My real value of n is 1000

1 Answer 1

2

You can use format to create the string for the filename

f = open('test{}.txt'.format(i), 'ab')

So your code could be modified to

import numpy as np
n = 5
g = my_func()
for i in range(n):
    with open('test{}.txt'.format(i), 'ab') as f:
        np.savetxt(f, g, fmt='%.0f', newline=" ")
Sign up to request clarification or add additional context in comments.

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.