在Python中删除临时文件 [英] Removing a temporary file in Python

查看:889
本文介绍了在Python中删除临时文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我现有的用于压缩文件夹的代码,该文件夹主要是从这里的帮助中整理到的:

This is my existing code to zip a folder which I have put together mostly from help on here:

#!/usr/bin/env python

import os
import sys
import datetime

now = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")
target_dir = '/var/lib/data'
temp_dir='/tmp'

zip = zipfile.ZipFile(os.path.join(temp_dir, now+".zip"), 'w', zipfile.ZIP_DEFLATED)
rootlen = len(target_dir) + 1
for base, dirs, files in os.walk(target_dir):
   for file in files:
      fn = os.path.join(base, file)
      zip.write(fn, fn[rootlen:])

如果我想删除操作结束时刚刚创建的zip文件,最好的命令是这个吗?

If I wanted to remove the zip file I just created at the end of the opperation, would the best command be this?

os.remove.join(temp_dir, now+".zip")

推荐答案

os.remove(os.path.join(temp_dir, now + ".zip"))会很好.

但是,您应该确保在每种情况下都能正确执行它.

However, you should ensure that it is executed properly in every case you want it to.

无论如何要删除它,您都可以

If it is to be removed in any case, you could do

create it
try:
    work with it
finally:
    remove it

但是在这种情况下,您也可以使用tempfile模块:

But in this case, you could as well use the tempfile module:

import tempfile
with tempfile.NamedTemporaryFile(suffix='.zip') as t:
    z = zipfile.ZipFile(t.name, 'w') # re-create it
    do stuff with z
# after the with clause, the file is gone.

但是,如果您只希望它在特殊情况下(成功,出错,...)消失,则您会选择os.remove(os.path.join(temp_dir, now+".zip")),并且在删除文件时都应使用它.

If, however, you want it to be gone only under special circumstances (on success, on error, ...) you are stuck with os.remove(os.path.join(temp_dir, now+".zip")) and you should use it whenever the file is to be deleted.

try:
    do_stuff
except VerySpecialException:
    os.remove(os.path.join(temp_dir, now+".zip")) # do that here for a special exception?
    raise # re-raise
except: # only use a bare except if you intend to re-raise
    os.remove(os.path.join(temp_dir, now+".zip")) # or here for all exceptions?
    raise # re-raise
else:
    os.remove(os.path.join(temp_dir, now+".zip")) # or here for success?

这篇关于在Python中删除临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆