This is a continuation from a question that I had yesterday. I am trying to open a text file that contains a list of numbers. I want to write these numbers to a new file multiple times. The purpose of the loop is to be able to write the source list multiple times. In this example, I want to print a list of 100 numbers 10 times so I end up with a list of 1000 numbers in my output file. This is the code that I am working with:
i = 10
while i > 0:
with open ('C:/TestReq_100 Records.txt', 'r') as ipf:
for line in ipf:
num = line.strip()
filename = 'processed.txt'
with open('processed.txt', 'w') as opf:
opf('%s' %num)
## print num
i = i - 1
If I comment out the code related to writing to file and use the print command in the interpreter, the code does what I want. I just can’t seem to get the same output in a text file. Again, I am not a student. Just trying to create files for use in my Company’s software for testing purposes…thanks!
In addition to Levon’s answer, there are a few issues with your current program.
Rather than manually initializing and decrementing an index, try using
xrangeto accomplish the same task in a more concise way.You’re overwriting processed.txt for each number; you should open it at the same time as the input file.
What is the purpose of
i? As it stands, your program is going to do the exact same thing 10 times becauseiis never used inside the loop.'%s' % numdoes nothing special whennumis already a string.That said, here’s a cleaner version of your program, although
istill does nothing in particular:You may want to clarify the intended output of this program for a better answer.
EDIT: Here is a more efficient solution for copying a file into a new file multiple times: