Reputation: 53
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
file2.write(new_string)
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.
EDIT: inserting file2.close() after the loop worked, all 1189 lines are in the second file now, but why?
Upvotes: 1
Views: 141
Reputation: 531
Your file1
and file2
point to the same file in the code sample you have given.
Upvotes: 1
Reputation: 4399
Do you close the file you're writing to, i.e. execute file2.close()
after the loop?
Upvotes: 1