Computer >> Máy Tính >  >> Lập trình >> Python

Làm thế nào để nén một thư mục một cách đệ quy bằng Python?


Sử dụng mô-đun zipfile để tạo một kho lưu trữ zip của một thư mục. Đi bộ cây thư mục bằng cách sử dụng os.walk và thêm tất cả các tệp trong đó một cách đệ quy.

ví dụ

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))
zipf = zipfile.ZipFile('Zipped_file.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('./my_folder', zipf)
zipf.close()

Đoạn mã trên sẽ nén nội dung của my_folder trong một tệp 'Zipped_file.zip'. và lưu trữ nó trong thư mục hiện tại.