【问题标题】:Removing a temporary file in Python在 Python 中删除临时文件
【发布时间】:2012-11-19 23:00:06
【问题描述】:

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

#!/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 文件,最好的命令是这个吗?

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

【问题讨论】:

  • 是的。如果您要多次使用它,您也可以将文件名保存在变量中,例如 filename
  • 应该是os.remove(os.path.join(...))?
  • ^ 去掉单引号,然后是的,就是这样。
  • 我认为他的意思是使用将某些东西标记为代码的`类型引号......
  • filename = os.path.join(temp_dir, now+".zip")。然后你可以使用zipfile.ZipFile(filename, 'w', …)os.remove(filename)

标签: python join zip


【解决方案1】:

os.remove(os.path.join(temp_dir, now + ".zip")) 没问题。

但是,您应该确保它在您希望的每种情况下都正确执行。

如果要在任何情况下删除它,你可以这样做

create it
try:
    work with it
finally:
    remove it

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

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")) 卡住,并且您应该在要删除文件时使用它。

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?

【讨论】:

  • 有趣的是,甚至还有一个用于临时文件的模块。感谢分享!
【解决方案2】:

这将是这样做的方式:

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

玩得开心,迈克

【讨论】:

    【解决方案3】:

    考虑使用 Python 的 built in temporary file library。它在关闭时处理临时文件的清理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-04
      • 2013-11-01
      • 1970-01-01
      相关资源
      最近更新 更多