Duyệt cây thư mục với os.walk(), thêm từng file vào ZipFile.
Ví dụ hoàn chỉnh
import os
import zipfile
def zipdir(path, ziph):
for root, dirs, files in os.walk(path):
for file in files:
filepath = os.path.join(root, file)
# arcname: đường dẫn bên trong zip (relative)
arcname = os.path.relpath(filepath, start=path)
ziph.write(filepath, arcname)
zipf = zipfile.ZipFile('Zipped_file.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('./my_folder', zipf)
zipf.close()
print("Đã tạo Zipped_file.zip")
Giải thích
os.walk(path)— sinh (root, dirs, files) cho từng thư mục con.os.path.relpath(filepath, start=path)— lấy đường dẫn tương đối để lưu trong zip (không chứa thư mục gốc).ZIP_DEFLATED— nén (cần zlib).ZIP_STORED— chỉ lưu, không nén.
Python 3.7+: pathlib
from pathlib import Path
import zipfile
with zipfile.ZipFile('out.zip', 'w', zipfile.ZIP_DEFLATED) as zf:
for file in Path('my_folder').rglob('*'):
if file.is_file():
zf.write(file, file.relative_to('my_folder'))