python shutil copy function missing last few lines

天涯浪子 提交于 2019-12-25 03:48:04

问题


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?


回答1:


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.


来源:https://stackoverflow.com/questions/15303555/python-shutil-copy-function-missing-last-few-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!