1

I have a python script that generates a large text file that needs a specific filename that will FTPd later. After creating the file it copies it to a new location while modifying the date to reflect the date sent. The only problem is that the copied file is missing several of the last lines of the original.

from shutil import copy

// file 1 creation

copy("file1.txt", "backup_folder/file1_date.txt")

What might be causing this? Could the original file not be finished being written to causing the copy to just get what is there?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

5

You must make sure that whatever creates file1.txt has closed the file handle.

File writing is buffered, and if you do not close the file, the buffer is not flushed. The missing data at the end of a file is still sitting in that buffer.

Preferably you ensure that the file is closed by using the file object as a context manager:

with open('file1.txt', 'w') as openfile:
    # write to openfile

# openfile is automatically closed once you step outside the `with` block.
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343