这是我现有的代码来压缩一个文件夹,我把它放在一起主要来自这里的帮助:
#!/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")
解决方法:
os.remove(os.path.join(temp_dir,现在是“.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,现在是“.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?
标签:python,join,zip