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

ไฟล์ถูกเพิ่มไปยังไฟล์ tar โดยใช้ Python อย่างไร


ใช้โมดูล tarfile เพื่อสร้างไฟล์ zip ของไดเร็กทอรี เดินโครงสร้างไดเรกทอรีโดยใช้ os.walk และเพิ่มไฟล์ทั้งหมดในนั้นซ้ำๆ

ตัวอย่าง

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:
                tar_handle.add(os.path.join(root, file))
tardir('./my_folder', 'sample.tar.gz')
tar.close()

โค้ดด้านบนจะบีบอัดเนื้อหาของ my_folder ในไฟล์ 'sample.tar.gz' และเก็บไว้ในไดเร็กทอรีปัจจุบัน