python - Shutil 复制命令写入 0 字节文件复制临时文件

标签 python shutil temp

我有另一种方法调用此函数 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/

相关文章:

c++ - 获取用户临时文件夹路径 C++

oracle - 无法在表空间 TEMP 中将临时段扩展 128

python - 我如何在 Sphinx 中定义应该使用哪些 .rst 文件和目录?

Python递归查找文件并移动到一个目标目录

python - 为什么 PyCharm 不允许在方法命名中使用大写字母?

python |移动用户创建的文件夹中的特定文件

python - 如何通过将文件名与文件夹名称匹配来将文件移动到不同的目录并移动到相应的文件夹中?

tomcat8 - Apache Tomcat 8.5.40 临时目录中的 safeToDelete.tmp 文件的用途是什么?

Python openpyxl : Read only mode returns a different row count

python - python 3作业出错