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

Tạo zip archive từ thư mục trong Python (zipfile)

Giống bài 1003107749/1003107712: tạo file zip từ thư mục dùng zipfile.ZipFile mode 'w'.

Code ngắn gọn

import os
import zipfile

with zipfile.ZipFile('archive.zip', 'w', zipfile.ZIP_DEFLATED) as zf:
    for root, dirs, files in os.walk('my_folder'):
        for file in files:
            filepath = os.path.join(root, file)
            arcname = os.path.relpath(filepath, 'my_folder')
            zf.write(filepath, arcname)

One-liner cho file đơn

import zipfile
zipfile.ZipFile('single.zip', 'w').write('file.txt')  # cần close() hoặc dùng with

Thêm file vào zip đã có

with zipfile.ZipFile('archive.zip', 'a', zipfile.ZIP_DEFLATED) as zf:
    zf.write('new_file.txt')