schnimmy schnimmy -4 years ago 121
Python Question

python read from file write to other file

file1 = open('/path/to/file1.txt', "r")
file2 = open('/path/to/file2.txt', "wa")
counter = 1

for line in file1:
new_string = str(counter) + '\t' + line
counter += 1

I am trying to add a number to the beginning of every line in a file and append this line by line to a new file. There are 1189 lines of text in the original file and despite a number of attempts I only get 1168 lines in the new file. What's going on?

I added a print statement ( print str(counter) + " " + line), all the lines from the original file get printed out with the expected number beside them. The counter variable is 1190 after the loop runs.

inserting file2.close() after the loop worked, all 1189 lines are in the second file now, but why?

Answer Source

Do you close the file you're writing to, i.e. execute file2.close() after the loop?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download