Saul_Tigh
Saul_Tigh

Reputation: 199

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'

Upvotes: 5

Views: 8579

Answers (4)

PaulMcG
PaulMcG

Reputation: 63782

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.

Upvotes: 8

sharjeel
sharjeel

Reputation: 6035

You haven't given the full traceback but I'm almost sure that the error is because by the time tmp_me() returns, the temporary files have been deleted. You return the names of two temporary created files and their objects named tmp and tmp_1 are destroyed when the function returns, deleting along the files they created. What you get outside is only names of two temporary files which no more exist now and hence the error while trying to compare them.

According to the documentation of tempfile.NamedTemporaryFile:

If delete is true (the default), the file is deleted as soon as it is closed.

Either pass default as False to your NameTemporaryFile calls, in which you should delete the files yourself. Or better and preferred method would be to return the objects instead of their names and from the exit_dialog() method pass the .name s to filecmp.cmp

import tempfile
def tmp_me():
    tmp1 = tempfile.NamedTemporaryFile()
    tmp2 = tempfile.NamedTemporaryFile()
    return [tmp1, tmp2]


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

exit_dialog()

Upvotes: 4

Imran
Imran

Reputation: 91119

Here's the full error message I get

WindowsError: [Error 2] The system cannot find the file specified: 'c:\\users\\imran\\appdata\\local\\temp\\tmpqh7dfp'

This is happening because reference to the temp file objects were lost when tmp_me() function returned, and temp files were deleted from disk when the variables were garbage collected.

You could return the temp file objects from tmp_me(), but then you'll have to close the files first before you could test them with filecmp.cmp

Upvotes: 2

Rudi Visser
Rudi Visser

Reputation: 22019

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)

Upvotes: 12

Related Questions