python临时文件

2024-06-01 04:46:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

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()

我需要比较这两个临时文件,但总是出现这样的错误:

WindowsError: [Error 2] : 'c:\\users\\Saul_Tigh\\appdata\\local\\temp\\tmpbkpmeq'

Tags: nameimport密码defexittempfiletmpfilecmp
2条回答

错误2是找不到文件(找不到错误文件)。

NamedTemporaryFile具有默认设置为Truedelete参数。您确定在返回tmp_me方法时不会立即删除该文件吗?

您可以尝试使用:

tempfile.NamedTemporaryFile(delete=False)

您还没有给出完整的回溯,但我几乎可以肯定,错误是因为当tmp_me()返回时,临时文件已被删除。返回两个临时创建的文件的名称,当函数返回时,它们名为tmp和tmp_1的对象将被销毁,同时删除它们创建的文件。你得到的只是两个暂时文件的名称,现在已经不存在了,因此在试图比较它们时出错。

根据tempfile.NamedTemporaryFile的文档:

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

将默认值作为False传递给NameTemporaryFile调用,在该调用中,您应该自己删除文件。或者更好的首选方法是返回对象而不是它们的名称,并从exit_dialog()方法将.name s传递给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()

相关问题 更多 >