我有另一种方法调用此函数 3 次来写入 3 个不同的文件。前 2 个文件按预期复制到目标文件夹,第三个文件始终为零字节。如果我关闭删除功能,我可以看到所有 3 个临时文件均已成功写入。代码没有报告错误,但在过程结束时第三个文件始终为空。
有谁知道为什么这会失败三分之一次?
def write_file(file_destination: str, content: bytes):
with tempfile.NamedTemporaryFile() as fp:
fp.write(content)
shutil.copy(fp.name, file_destination)
以下变体有效,但是,我想了解为什么上面的代码中前两个文件有效而第三个文件无效。
def write_file(file_destination: str, content: bytes):
with tempfile.NamedTemporaryFile(delete=False) as fp:
fp.write(content)
shutil.copy(fp.name, file_destination)
os.remove(fp.name)
最佳答案
这是因为当您执行复制时,内容
尚未写入磁盘。发生这种情况是因为写入会被缓冲,并且并不总是在调用 file.write
后立即发生。
要确保内容在给定点写入磁盘,您可以使用 file.flush
。
就您的情况而言,将代码更改为:
def write_file(file_destination: str, content: bytes):
with tempfile.NamedTemporaryFile() as fp:
fp.write(content)
fp.flush()
shutil.copy(fp.name, file_destination)
有关内容何时实际写入磁盘的更多信息,您可以参阅 io.BufferedWriter
的文档。相关部分是:
The buffer will be written out to the underlying RawIOBase object under various conditions, including:
- when the buffer gets too small for all pending data;
- when flush() is called;
- when a seek() is requested (for BufferedRandom objects);
- when the BufferedWriter object is closed or destroyed.
因此,在您的第一个示例中,它可能只能在某些时候起作用,因为这些时候您正在写入的内容超出了缓冲区,因此需要立即写出。
相反,您的第二个示例有效,因为当您退出 with
block 时,文件将关闭,因此需要刷新缓冲区并将其写入磁盘。
关于python - Shutil 复制命令写入 0 字节文件复制临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55236493/