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

Thêm file vào tar.gz bằng Python (tarfile + os.walk)

Tương tự zip, dùng tarfile + os.walk tạo archive nén.

Ví dụ

import os
import tarfile

def tardir(path, tar_name):
    with tarfile.open(tar_name, "w:gz") as tar_handle:
        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)
                tar_handle.add(filepath, arcname=arcname)

tardir('./my_folder', 'sample.tar.gz')
print("Đã tạo sample.tar.gz")

Lưu ý

  • tar_handle.add(filepath, arcname=...) — arcname đặt tên bên trong archive.
  • Mode w:gz (gzip), w:bz2 (bzip2), w:xz (lzma), w (không nén).
  • Tar giữ permission, ownership, symlink tốt hơn zip.