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

前端 未结 5 1476
孤城傲影
孤城傲影 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:37

    There isn't one directly, but you can use a combination of tempfile and shutil.copy2 to achieve the same result:

    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
    

    You'll need to deal with removing the temporary file in the caller, though.

提交回复
热议问题