问题描述
如何在 Python 中创建目录结构的 zip 存档?
How can I create a zip archive of a directory structure in Python?
修改 2021 年 9 月 20 日:
请使用带有 make_archive from shutil 的解决方案,因为它是最方便且获得最多投票的解决方案.原发问者不再注册
Edit 20th of September 2021:
Please use the solution with make_archive from shutil as it is the most convenient one and has the most upvotes. The original questioner isn't registered anymore
修改时间:2021 年 11 月 3 日请注意,从 Python 3.4 开始,在 Python 中处理文件时,建议使用 Path 对象而不是纯字符串.但是,shutil.make_archive
不接受 Path 对象,但 zipfile
接受.
3rd of November 2021Note that starting from Python 3.4 it is recommended to use Path objects instead of plain strings when working with files in Python. However, shutil.make_archive
does not accept Path objects, but zipfile
does.
推荐答案
正如其他人所指出的,你应该使用 zip 文件.该文档会告诉您哪些函数可用,但并未真正解释如何使用它们来压缩整个目录.我认为用一些示例代码来解释最简单:
As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code:
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, '..')))
zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('tmp/', zipf)
zipf.close()
这篇关于如何创建目录的 zip 存档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!