首页 > 解决方案 > 在 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 方法。

标签: pythonfile

解决方案


你可以试试这个代码片段。根据安全问题,我建议使用 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)

推荐阅读