python - 在 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)
推荐阅读
- ruby-on-rails - 为什么我的视图在未调用时显示实例?
- c# - 重启游戏时如何保存实例化生成对象
- python - 如何使用 json_normalize 展平嵌套 Json 数据
- javascript - 将 Firebase 方法转换为异步等待
- c# - 无法将 Json 结果放入列表中
- php - 使用 OAuth2.0 在 PHP 中包含 Google Sitemap Api
- clojure - 如何循环打印?
- php - APP_ENV 和 APP_DEBUG 常量对 Symfony 应用程序有什么影响?
- angular - 获取 Angular 组件的滚动位置
- amp-story - 如何将 none-amp-page 引用到 amphtml 页面和 amp 故事页面