Skip to content

[Python] 使用 tarfile 壓縮、解壓縮檔案

tarfile 是 Python 中的一個標準模組,可用於操作 gzip、bz2、lzma 等格式的壓縮、解壓縮 —— 若是以副檔名來分辨,那就是 tar.gz、tar.bz2、tar.xz 等三種副檔名格式的檔案,通通可以透過 Python 中的 tarfile 來操作。

以下,先介紹官方文件中所列的幾種操作模式 (網址連結於文末),再列出簡單的範例程式碼。


open() 操作模式

模式操作
‘r’ or ‘r:*’Open for reading with transparent compression (recommended).
‘r:’Open for reading exclusively without compression.
‘r:gz’Open for reading with gzip compression.
r:bz2′Open for reading with bzip2 compression.
‘r:xz’Open for reading with lzma compression.
'x' or 'x:'Create a tarfile exclusively without compression. Raise an FileExistsError exception if it already exists.
‘x:gz’Create a tarfile with gzip compression. Raise an FileExistsError exception if it already exists.
‘x:bz2’Create a tarfile with bzip2 compression. Raise an FileExistsError exception if it already exists.
‘x:xz’Create a tarfile with lzma compression. Raise an FileExistsError exception if it already exists.
‘a’ or ‘a:’Open for appending with no compression. The file is created if it does not exist.
‘w’ or ‘w:’Open for uncompressed writing.
‘w:gz’Open for gzip compressed writing.
‘w:bz2’Open for bzip2 compressed writing.
‘w:xz’Open for lzma compressed writing.
https://docs.python.org/3/library/tarfile.html

以上就是在 tarfile 中的不同操作模式。


範例程式

在 Python 中,tarfilezipfile 的用法極其相似,我基本上就是從另外一篇紀錄 zipfile 的筆記中改過來的。

首先,假設我要壓縮的資料夾為 test/,是我電腦中真實存在的一個資料夾:

資料夾底下存在著 test_01.txt 和 test_02.txt 兩份檔案


使用 tarfile 壓縮檔案 (以 tar.gz 為例)

# coding: utf-8
import os
import tarfile


# tarfile example
def tar_dir(path):
    tar = tarfile.open('test.tar.gz', 'w:gz')
   
    for root, dirs, files in os.walk(path):
        for file_name in files:
            tar.add(os.path.join(root, file_name))

    tar.close()


if __name__ == '__main__':
    path = 'test'
    tar_dir(path)



使用 tarfile 解壓縮檔案 (以 tar.gz 為例)

# coding: utf-8
import os
import tarfile


# tarfile example
def tar_extract(file_path):
    tar = tarfile.open(file_path, 'r:gz')
    tar.extractall()


if __name__ == '__main__':
    file_path = 'test.tar.gz'
    tar_extract(file_path)



References


References

Leave a Reply