yam*_*shi 1 python file-io python-3.x
我有一个 python 脚本,它生成一个大文本文件,该文件需要一个特定的文件名,稍后将使用 FTPd。创建文件后,它会将其复制到新位置,同时修改日期以反映发送日期。唯一的问题是复制的文件缺少原始文件的最后几行。
from shutil import copy
// file 1 creation
copy("file1.txt", "backup_folder/file1_date.txt")
Run Code Online (Sandbox Code Playgroud)
这可能是什么原因造成的?原始文件是否未完成写入导致副本只是获取那里的内容?
您必须确保创建的任何内容file1.txt都已关闭文件句柄。
文件写入是缓冲的,如果不关闭文件,则不会刷新缓冲区。文件末尾丢失的数据仍然位于该缓冲区中。
最好通过将文件对象用作上下文管理器来确保文件已关闭:
with open('file1.txt', 'w') as openfile:
# write to openfile
# openfile is automatically closed once you step outside the `with` block.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
753 次 |
| 最近记录: |