Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Nén thư mục đệ quy thành file zip trong Python (zipfile)

Tương tự bài 1003107710/1003107712: zipfile + os.walk nén đệ quy.

Code chuẩn

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 = os.path.relpath(filepath, start=path)
            ziph.write(filepath, arcname)

with zipfile.ZipFile('Zipped_file.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
    zipdir('./my_folder', zipf)

print("Đã nén my_folder → Zipped_file.zip")

Loại trừ file/thư mục (ví dụ: .git, __pycache__)

EXCLUDE = {'.git', '__pycache__', '.venv', '*.pyc'}

def zipdir(path, ziph):
    for root, dirs, files in os.walk(path):
        # Modify dirs in-place để os.walk không đi vào
        dirs[:] = [d for d in dirs if d not in EXCLUDE]
        for file in files:
            if not any(file.endswith(pat.replace('*', '')) for pat in EXCLUDE if '*' in pat):
                filepath = os.path.join(root, file)
                arcname = os.path.relpath(filepath, start=path)
                ziph.write(filepath, arcname)