我运行了以下代码:
import zipfile
import glob
import datetime
import os
from collections import defaultdict
from shutil import copyfile
src = 'X:\\'
for name in glob.glob('X:\*'):
print name
dict_date = defaultdict(lambda : defaultdict(list))
for fil in os.listdir(src):
if os.path.isfile(os.path.join(src, fil)):
date, logs = fil.split('_')[0], fil.split('_')[2]
dict_date[date][logs].append(fil)
for date in dict_date:
for logs in dict_date[date]:
try:
os.makedirs(os.path.join(src, date, logs))
except os.error:
pass
for fil in dict_date[date][logs]:
copyfile(os.path.join(src, fil), os.path.join(src, date, logs, fil))
for date in dict_date:
with ZipFile(os.path.join(path, '{0}.zip'.format(date)), 'w') as myzip:
for logs in dict_date[date]:
for fil in os.listdir(os.path.join(path, date, logs)):
if fil.endswith('.log'):
myzip.write(os.path.join(path, date, logs, fil))
结果如下:
>>>
X:\082012
X:\092012
X:\20120830
X:\20120830_7Days_ISDA_Logs_HS.zip
X:\20121001
X:\20121002
X:\20121003
X:\20121004
X:\20121005
X:\20121006
X:\20121007
X:\20121008
X:\20121009
X:\20121010
X:\20121011
Traceback (most recent call last):
File "C:\Documents and Settings\tyoffe\Desktop\isda_zip.py", line 31, in <module>
with ZipFile(os.path.join(path, '{0}.zip'.format(date)), 'w') as myzip:
NameError: name 'ZipFile' is not defined
>>>
答案 0 :(得分:0)
你应该使用:
with zipfile.ZipFile(os.path.join(path, '{0}.zip'.format(date)), 'w') as myzip:
或者您应该这样做:
from zipfile import ZipFile