蟒蛇shutil复制功能缺少最后几行 [英] python shutil copy function missing last few lines

查看:157
本文介绍了蟒蛇shutil复制功能缺少最后几行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,可以生成一个大的文本文件,需要一个特定的文件名,以后再FTPd。创建文件后,将其复制到新位置,同时修改日期以反映发送日期。唯一的问题是复制的文件丢失了原来的几行。

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?

推荐答案

您必须确保无论如何创建 file1.txt 已关闭文件句柄。

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.

最好通过使用文件对象作为上下文管理器来确保文件被关闭: / b>

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.

这篇关于蟒蛇shutil复制功能缺少最后几行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆