1
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?

5
  • Why? You have to close the files, it is how is it. When closing the file you indicate that you have finished your work, so the OS can 'commit' all your changes to disk. Think the other way around, if there were no 'close' statement, your program will have to write to disk every time you write something, and this is clearly inefficient.
    – mosh442
    Feb 27, 2017 at 7:06
  • I can understand that if we don't close extra information may get written to the file, but why would information get deleted?
    – schnimmy
    Feb 28, 2017 at 8:39
  • The key point here is that there is no information deleted. When your code executes file2.write(new_string) this write doen't go to the file. It goes to buffer and then, flushed to the file. If you don't close the file you can lose your buffer.
    – mosh442
    Feb 28, 2017 at 15:50
  • Interesting, then why did it write the first 1168 lines with file.write() alone without the file.close() ?
    – schnimmy
    Feb 28, 2017 at 18:59
  • Python does not control when the buffer is flushed to the disk, this is up to the operating system. So It is the operating system who decides when to write the buffer. With close() you tell the operating system that you are finished so it will do all the writing.
    – mosh442
    Mar 1, 2017 at 6:16

2 Answers 2

1

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

2
  • no, i don't, how could that have an impact if there 21 lines missing?
    – schnimmy
    Feb 26, 2017 at 17:23
  • Try closing the file, so that all file buffers are flushed.
    – lukeg
    Feb 26, 2017 at 18:43
1

Your file1 and file2 point to the same file in the code sample you have given.

1
  • yeah i copied and pasted the path, but i am definitely using different files
    – schnimmy
    Feb 26, 2017 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.