Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเพิ่มไฟล์ลง Tar File ใน Python (tarfile + os.walk)

ใช้ tarfile สร้าง Tar Archive (รองรับ Compression) เดิน Directory Tree ด้วย os.walk

ฟังก์ชัน Tar Directory

import os
import tarfile

def tardir(path, tar_name):
    with tarfile.open(tar_name, "w:gz") as tar_handle:  # w:gz = write gzip compressed
        for root, dirs, files in os.walk(path):
            for file in files:
                filepath = os.path.join(root, file)
                tar_handle.add(filepath)  # add() รองรับ recursive เองได้ แต่ walk ให้ control มากกว่า

tardir('./my_folder', 'sample.tar.gz')

คำอธิบาย Mode Strings

Modeความหมาย
'w:'Write, ไม่ Compress
'w:gz'Write, Gzip Compress (.tar.gz)
'w:bz2'Write, Bzip2 Compress (.tar.bz2)
'w:xz'Write, LZMA Compress (.tar.xz)
'a:'Append (เพิ่มเข้า Archive ที่มีอยู่)
'r:'Read (Auto-detect Compression)

การควบคุม Archive Name (arcname)

>> with tarfile.open('sample.tar.gz', 'w:gz') as tf:
...     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')
...             tf.add(filepath, arcname=arcname)

เพิ่มไฟล์เดี่ยว

>> with tarfile.open('single.tar.gz', 'w:gz') as tf:
...     tf.add('file.txt')
...     tf.add('data.csv', arcname='new.csv')