Python shutil copy function skip the last few lines

I have a python script that generates a large text file that requires a specific file name, which will later be FTPd. After creating the file, it copies it to a new location, changing the date to reflect the sent date. The only problem is that some of the last lines of the original are missing from the copied file.

from shutil import copy // file 1 creation copy("file1.txt", "backup_folder/file1_date.txt") 

What could be the reason for this? Can the source file not be written to make the copy just get what's there?

0
source share
1 answer

You must make sure that everything file1.txt creates file1.txt the file descriptor.

The file record is buffered, and if you do not close the file, the buffer will not be cleared. Missing data at the end of the file is still in this buffer.

It is advisable that the file be closed using the file object as the context manager:

 with open('file1.txt', 'w') as openfile: # write to openfile # openfile is automatically closed once you step outside the `with` block. 
+3
source

All Articles