Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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:

create_temporary_copy(file_path)
like image 553
Gideon Avatar asked Jul 05 '11 18:07

Gideon


1 Answers

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.

like image 56
TorelTwiddler Avatar answered Oct 17 '22 03:10

TorelTwiddler