在Python中关闭临时文件时删除它



我有一个类似的函数:

def open_tmp():
tmp = mktemp()
copy('file.txt', tmp)
return open(tmp, 'rt')

我想在文件关闭时自动删除创建的临时文件,例如:

file = open_tmp()
# Do something with file
file.close()  # I want to remove the temporal file here

有可能吗?我想创建一个BaseIO的子类并重写close()函数,但我认为这是太多的工作,因为我必须重写所有的BaseIO方法。

您可以尝试下面的代码片段。根据安全考虑,我建议使用tempfile代替你的代码。

import os
import tempfile
new_file, file_path = tempfile.mkstemp()
try:
with os.fdopen(new_file, 'w') as temp_file:
# Do something with file
temp_file.write('write some dumy text in file')
finally:
os.remove(file_path)

我已经找到了解决方案:

import os
import tempfile
def open_tmp():
tmp = tempfile.mkstemp()
copy('file.txt', tmp)  # This copy the file.txt to tmp
file = open(tmp, 'rt')
old_close = file.close

def close():
old_close()
os.remove(tmp)
file.close = close
return file

最新更新