如何简洁地创建一个临时文件,它是python中另一个文件的副本

Gid*_*eon 11 python

我知道可以创建一个临时文件,并将要复制的文件的数据写入其中.我只是想知道是否有这样的功能:

create_temporary_copy(file_path)
Run Code Online (Sandbox Code Playgroud)

Tor*_*ler 22

没有一个直接的,但你可以使用的组合tempfileshutil.copy2达到相同的结果:

import tempfile, shutil, os
def create_temporary_copy(path):
    temp_dir = tempfile.gettempdir()
    temp_path = os.path.join(temp_dir, 'temp_file_name')
    shutil.copy2(path, temp_path)
    return temp_path
Run Code Online (Sandbox Code Playgroud)

但是,您需要处理删除调用方中的临时文件.

  • 我会使用 `temp_dir = tempfile.TemporaryDirectory()` 来代替。这样,您可以在完成后调用“temp_dir.close()”,该文件夹将自动删除。或者更好的是,使用 `with tempfile.TemporaryDirectory() as temp_dir:` (3认同)
  • 或者将函数中的前两行替换为:`fd, temp_path = tempfile.mkstemp()`。 (2认同)
  • 它不适用于 Windows。它会引发权限被拒绝错误。 (2认同)

Dav*_*nat 7

以下比所选答案更简洁(OP 的要求)。享受!

import tempfile, shutil, os
def create_temporary_copy(path):
  tmp = tempfile.NamedTemporaryFile(delete=True)
  shutil.copy2(path, tmp.name)
  return tmp.name
Run Code Online (Sandbox Code Playgroud)


use*_*026 6

这不是那么简洁,我想可能存在异常安全问题(例如,如果'original_path'不存在会发生什么,或者当文件打开时,temporary_copy对象超出范围)但是此代码添加一点RAII清理.直接使用NamedTemporaryFile的不同之处在于,不是以文件对象结束,而是最终得到一个文件,这偶尔也是可取的(例如,如果您打算调用其他代码来读取它,或者其他一些文件.)

import os,shutil,tempfile
class temporary_copy(object):

    def __init__(self,original_path):
        self.original_path = original_path

    def __enter__(self):
        temp_dir = tempfile.gettempdir()
        base_path = os.path.basename(self.original_path)
        self.path = os.path.join(temp_dir,base_path)
        shutil.copy2(self.original_path, self.path)
        return self.path

    def __exit__(self,exc_type, exc_val, exc_tb):
        os.remove(self.path)
Run Code Online (Sandbox Code Playgroud)

在你的代码中你写的:

with temporary_copy(path) as temporary_path_to_copy:
    ... do stuff with temporary_path_to_copy ...

# Here in the code, the copy should now have been deleted.
Run Code Online (Sandbox Code Playgroud)