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

时间:2011-07-05 18:59:56

标签: python

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

create_temporary_copy(file_path)

5 个答案:

答案 0 :(得分:17)

没有一个直接,但您可以使用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

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

答案 1 :(得分:5)

这并不简洁,我想可能存在异常安全问题(例如,如果原始路径不存在会发生什么,或者临时复制对象熄灭会发生什么?当你打开文件时范围,但这个代码添加了一点RAII清理。直接使用NamedTemporaryFile的不同之处在于,不是以文件对象结束,而是最终得到一个文件,这有时是合乎需要的(例如,如果您计划调用其他代码来读取它,或者其他类似的话。)< / p>

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)

在你的代码中你写道:

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.

答案 2 :(得分:2)

@ tramdas答案的一个变种,说明了这个文件无法在Windows上打开两次这一事实。此版本忽略了文件扩展名的保留。

import os, shutil, tempfile

def create_temporary_copy(src):
  # create the temporary file in read/write mode (r+)
  tf = tempfile.TemporaryFile(mode='r+b', prefix='__', suffix='.tmp')

  # on windows, we can't open the the file again, either manually
  # or indirectly via shutil.copy2, but we *can* copy
  # the file directly using file-like objects, which is what
  # TemporaryFile returns to us.
  # Use `with open` here to automatically close the source file
  with open(src,'r+b') as f:
    shutil.copyfileobj(f,tf)

  # display the name of the temporary file for diagnostic purposes
  print 'temp file:',tf.name

  # rewind the temporary file, otherwise things will go
  # tragically wrong on Windows
  tf.seek(0) 
  return tf

# make a temporary copy of the file 'foo.txt'
name = None

with create_temporary_copy('foo.txt') as temp:
  name = temp.name

  # prove that it exists
  print 'exists', os.path.isfile(name) # prints True

  # read all lines from the file
  i = 0
  for line in temp:
    print i,line.strip()
    i += 1

  # temp.close() is implicit using `with`

# prove that it has been deleted
print 'exists', os.path.isfile(name) # prints False

答案 3 :(得分:1)

与选择的答案相比,以下内容更简洁(OP的询问)。享受吧!

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

答案 4 :(得分:0)

略有不同(特别是我的用例需要preserve_extension功能,我喜欢&#34;自我清理&#34;功能):

import os, shutil, tempfile
def create_temporary_copy(src_file_name, preserve_extension=False):
    '''
    Copies the source file into a temporary file.
    Returns a _TemporaryFileWrapper, whose destructor deletes the temp file
    (i.e. the temp file is deleted when the object goes out of scope).
    '''
    tf_suffix=''
    if preserve_extension:
        _, tf_suffix = os.path.splitext(src_file_name)
    tf = tempfile.NamedTemporaryFile(suffix=tf_suffix)
    shutil.copy2(src_file_name, tf.name)
    return tf