how to concisely create a temporary file that is a copy of another file in python

前端 未结 5 1475
孤城傲影
孤城傲影 2021-01-07 23:24

I know that it is possible to create a temporary file, and write the data of the file I wish to copy to it. I was just wondering if there was a function like:



        
5条回答
  •  感动是毒
    2021-01-07 23:28

    A slight variation (in particular I needed the preserve_extension feature for my use case, and I like the "self-cleanup" feature):

    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
    

提交回复
热议问题