Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python temporary files

I have this code:

import tempfile
def tmp_me():
    tmp = tempfile.NamedTemporaryFile()
    tmp1 = tempfile.NamedTemporaryFile()
    lst = [tmp.name, tmp1.name]
    return lst

def exit_dialog():
    lst = tmp_me()
    print lst
    import filecmp
    eq = filecmp.cmp(lst[0],lst[1])
    print eq

exit_dialog()

I need to compare this 2 tempfiles, but i've always getting an error like this:

WindowsError: [Error 2] : 'c:\\users\\Saul_Tigh\\appdata\\local\\temp\\tmpbkpmeq'
like image 803
Saul_Tigh Avatar asked Apr 27 '11 10:04

Saul_Tigh


People also ask

Where does Python store temporary files?

This function returns name of directory to store temporary files. This name is generally obtained from tempdir environment variable. On Windows platform, it is generally either user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp.

How do I delete temp files in Python?

gettempdir() to get the directory where all the temp files are stored. After running the program, if you go to temp_dir (which is /tmp in my case – Linux), you can see that the newly created file 3 is not there. This proves that Python automatically deletes these temporary files after they are closed.

How do I view temp files?

To view and delete temp files, open the Start menu and type %temp% in the Search field. In Windows XP and prior, click the Run option in the Start menu and type %temp% in the Run field. Press Enter and a Temp folder should open.


2 Answers

Error 2 is that the file is not found (ERROR_FILE_NOT_FOUND).

NamedTemporaryFile has the delete parameter which is by default set to True. Are you sure that the file is not being immediately deleted at the return of your tmp_me method?

You could try using:

tempfile.NamedTemporaryFile(delete=False)
like image 109
Rudi Visser Avatar answered Oct 05 '22 07:10

Rudi Visser


Have temp_me return the list of the two temp files, instead of just their names (so they don't get garbage collected), and pull the names out in exit_dialog.

like image 21
PaulMcG Avatar answered Oct 05 '22 07:10

PaulMcG