ใช้โมดูล tarfile สร้าง Tar Archive (รองรับ Compression: gz, bz2, xz) จาก Directory
โค้ดสร้าง Tar (Complete)
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, path)
tar_handle.add(filepath, arcname=arcname)
tardir('./my_folder', 'sample.tar.gz')
คำอธิบาย
tarfile.open(name, 'w:gz')- สร้าง .tar.gz (Gzip Compressed Tar)os.walk(path)- เดิน Directory Treetar_handle.add(filepath, arcname=...)- เพิ่มไฟล์พร้อมระบุชื่อใน Archive
Compression Options
>> # ไม่ Compress
>>> tarfile.open('archive.tar', 'w:')
>>> # Gzip (Common, Fast, Good Ratio)
>>> tarfile.open('archive.tar.gz', 'w:gz')
>>> # Bzip2 (Better Ratio, Slower)
>>> tarfile.open('archive.tar.bz2', 'w:bz2')
>>> # LZMA/xz (Best Ratio, Slowest)
>>> tarfile.open('archive.tar.xz', 'w:xz')
เพิ่มไฟล์จาก Memory (Bytes)
>> import io, tarfile
>>> with tarfile.open('mem.tar.gz', 'w:gz') as tf:
... data = b'Hello from memory!'
... info = tarfile.TarInfo(name='hello.txt')
... info.size = len(data)
... tf.addfile(info, io.BytesIO(data))
ตรวจสอบเนื้อหา Tar
>> with tarfile.open('sample.tar.gz', 'r') as tf:
... for member in tf.getmembers():
... print(member.name, member.size, member.mtime)