1

I would like to open several files and save the outputs. This is the operation that I would like to script iteratively for {i}=76 files.txt. The reference_file.txt is always the same for each of the 76 files I want to manipulate.

import numpy as np
a=np.loadtxt('filename{i}.txt')
b=np.loadtxt('reference_file.txt')
np.savetxt('output{i}.txt', np.subtract(a,b))

and then end the script.

1 Answer 1

1

Looping python using a for command. range(0, 76) is a range object. To keep things simple it's like a list of 0 to 75. That means i will take the values of 0, 1, 2, .., 75 each iteration.

Extracted b out of the loop since it's not depended on i

Using string format to use i in the string. read about it here or here

import numpy as np

b = np.loadtxt('reference_file.txt')
for i in range(0, 76):
    a = np.loadtxt("filename{}.txt".format(i))
    np.savetxt("output{}.txt".format(i), np.subtract(a,b))
Sign up to request clarification or add additional context in comments.

3 Comments

I suggest better variable names than b and a. Also since Python 3.6: np.loadtxt(f"filename{i}.txt")
I did not know that, and this is way more elegant than the format method I usually use
Also new to me! Thanks @Dan !

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.