Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create temporary file in Python that will be deleted automatically after sometime

Is it possible to create temporary files in python that will be deleted after some time? I checked tempfile library which generates temporary files and directories.

tempfile.TemporaryFile : This function creates tempfile which will be destroyed as soon as closed.

tempfile.NamedTemporaryFile: This function accepts a parameter delete. If delete is given the value false while calling the function the file will not be deleted on close.

What I need is a temp file which I should be able to read with its name for some time even after I close it. However, It should be deleted automatically after some time.

What is the easiest way to do this in Python 2.7?

like image 774
Codeformer Avatar asked Nov 08 '22 20:11

Codeformer


1 Answers

If you only need to run the file at intervals within your Python program, you can use it as a context manager:

def main(file_object):
    # Can read and write to file_object at any time within this function

if __name__ == '__main__':
    with tempfile.NamedTemporaryFile() as file_object:
        main(file_object)
        # Can still use file_object
    # file_object is referencing a closed and deleted file here

If you need to be able to open it outside of the Python program, say after main is over, like in a process that runs asyncronously, you should probably look for a more permenant solution (e.g. allowing the user to specify the file name.)

If you really needed to have a temporary auto-deleting file, you can start a threading.Timer to delete it after some time, but make sure that your program deletes it even if it is stopped before the timer ends.

like image 187
Artyer Avatar answered Nov 15 '22 05:11

Artyer