我试图压缩我创建的日志文件,但没有写入任何内容! 代码:
def del_files():
'''Adapted from answer @ http://stackoverflow.com/questions/7217196/python-delete-old-files by jterrace'''
dir_to_search = os.path.join(os.getcwd(),'log')
for dirpath, dirnames, filenames in os.walk(dir_to_search):
for file in filenames:
curpath = os.path.join(dirpath, file)
log(curpath)
if curpath != path:
log("Archiving old log files...")
with zipfile.ZipFile("log_old.zip", "w") as ZipFile:
ZipFile.write(curpath)
ZipFile.close()
log("archived")
答案 0 :(得分:0)
首先,您将在每次迭代时覆盖输出zip文件:
with zipfile.ZipFile("log_old.zip", "w") as ZipFile:
模式"w"
表示创建新文件或截断现有文件。可能你的意思是附加到zip文件,在这种情况下,可以使用模式"a"
打开它以追加。或者你可以在外部for循环之外打开zip文件。
您的代码应该导致log_old.zip
包含一个文件 - os.walk()
找到的最后一个文件。
在主循环之外打开存档更好,因为文件只会打开一次,并且由于上下文管理器(with
)而自动关闭:
with zipfile.ZipFile("log_old.zip", "w") as zf:
dir_to_search = os.path.join(os.getcwd(), 'log')
for dirpath, dirnames, filenames in os.walk(dir_to_search):
for file in filenames:
curpath = os.path.join(dirpath, file)
zf.write(curpath)