如何使用 Python (zipfile) 递归压缩文件夹
此脚本将文件夹 myfolder 递归压缩到 myzip。注意空目录不会被复制到 ZIP 中。
zip_folder_recursive.py
#!/usr/bin/env python3
import zipfile
import os
# 此文件夹
folder = "myfolder"
with zipfile.ZipFile(f"{folder}.zip", "w") as outzip:
for subdir, dirs, files in os.walk(folder):
for file in files:
# 读取文件
srcpath = os.path.join(subdir, file)
dstpath_in_zip = os.path.relpath(srcpath, start=folder)
with open(srcpath, 'rb') as infile:
# 写入 zip
outzip.writestr(dstpath_in_zip, infile.read())Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow