Python 临时文件

5 投票
4 回答
8525 浏览
提问于 2025-04-16 16:30

我有这段代码:

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'

4 个回答

4

你没有提供完整的错误追踪信息,但我几乎可以肯定,错误的原因是当函数 tmp_me() 返回时,临时文件已经被删除了。你返回了两个临时创建的文件的名字,而它们的对象 tmp 和 tmp_1 在函数返回时就被销毁了,这样它们创建的文件也就被删除了。你在外面得到的只是两个临时文件的名字,但这些文件现在已经不存在了,因此在尝试比较它们时就会出错。

根据 tempfile.NamedTemporaryFile 的文档:

如果 delete 设置为真(默认值),文件在关闭后会立即被删除。

你可以在调用 NameTemporaryFile 时将 delete 设置为 False,这样你就需要自己去删除这些文件。或者更好的方法是返回对象本身,而不是它们的名字,然后在 exit_dialog() 方法中将 .name 传给 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()
8

temp_me 返回两个临时文件的列表,而不仅仅是它们的名字(这样它们就不会被系统自动清理掉),然后在 exit_dialog 中提取这些名字。

12

错误2是文件没有找到(ERROR_FILE_NOT_FOUND)。

NamedTemporaryFile 有一个叫 delete 的参数,默认值是 True。你确定在你的 tmp_me 方法返回时,文件没有被立刻删除吗?

你可以试试使用:

tempfile.NamedTemporaryFile(delete=False)

撰写回答