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

Tạo file tar.gz trong Python (tarfile)

Tạo archive tar nén gzip dùng tarfile.open('w:gz') + os.walk.

Code mẫu

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")

Các chế độ nén

  • w:gz — gzip (nhanh, phổ biến).
  • w:bz2 — bzip2 (nén tốt hơn, chậm hơn).
  • w:xz — lzma (nén tốt nhất, chậm nhất).
  • w — không nén (plain tar).

Thêm file đơn lẻ

with tarfile.open('single.tar.gz', 'w:gz') as tf:
    tf.add('large_file.dat', arcname='data.dat')