python临时文件
我有以下代码:python临时文件,python,temporary-files,Python,Temporary Files,我有以下代码: 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 = fil
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'
错误2是找不到文件(错误为找不到文件)
NamedTemporaryFile
具有delete
参数,该参数默认设置为True
。您确定在返回tmp\u me
方法时不会立即删除该文件吗
您可以尝试使用:
tempfile.NamedTemporaryFile(delete=False)
这是我收到的完整错误消息
WindowsError: [Error 2] The system cannot find the file specified: 'c:\\users\\imran\\appdata\\local\\temp\\tmpqh7dfp'
发生这种情况的原因是,当tmp_me()
函数返回时,对临时文件对象的引用丢失,并且在对变量进行垃圾收集时,临时文件从磁盘中删除
您可以从
tmp\u me()
返回临时文件对象,但在使用filecmp.cmp
测试它们之前,您必须先关闭这些文件。您还没有给出完整的回溯,但我几乎可以肯定错误是因为在tmp\u me()返回时,临时文件已被删除。返回两个临时创建的文件的名称,当函数返回时,名为tmp和tmp_1的对象将被销毁,并删除它们创建的文件。您在外部得到的只是两个临时文件的名称,它们现在已不存在,因此在尝试比较它们时会出现错误
根据以下文件:
如果delete为true(默认值),则文件一关闭即被删除
将默认值作为False传递给NameTemporaryFile调用,在该调用中,您应该自己删除文件。或者更好、更可取的方法是返回对象而不是它们的名称,并从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()
让
temp\u me
返回两个temp文件的列表,而不仅仅是它们的名称(这样它们就不会被垃圾收集),然后在exit\u对话框中拉出名称
这不是完整的回溯。是的,我试图在我的小项目中使用它。我正在用Tkinter.Nah写一个简单的记事本。最好将物体保持在附近。+1。我想这就是发生的事情。当函数返回且文件被删除时,局部变量tmp
和tmp1
会被销毁。@Ignacio,你是对的,但我认为这个应用程序还没有接近完成,所以希望在完成时会有所不同。当函数返回时,局部变量会被销毁。这将调用对象上的析构函数(除非它们是使用delete=False
创建的),临时文件将被删除。是局部变量的破坏触发了你提到的整个事件链,他只引用了一次。函数内部。因此,返回确实导致他们得到回收。