如何使用 Python 建立 tar 檔案?


tar 檔案中的 TAR 指的是 Tape Archive Files(磁帶歸檔檔案)。tar 檔案是歸檔檔案,允許您將多個檔案儲存在一個檔案中。開源軟體通常使用 tar 檔案進行分發。

tar 檔案通常以 .tar 結尾,但在使用 gzip 等工具壓縮後,其結尾為 .tar.gz。

Python tar 檔案的各種開啟檔案模式

  • r − 開啟並讀取 TAR 檔案。
  • r − 開啟並讀取未壓縮的 TAR 檔案。
  • w 或 w − 開啟 TAR 檔案進行未壓縮寫入。
  • a 或 a − 開啟 TAR 檔案進行未壓縮追加。
  • r:gz − 開啟使用 gzip 壓縮的 TAR 檔案進行讀取。
  • w:gz − 開啟使用 gzip 壓縮的 TAR 檔案進行寫入。
  • r:bz2 − 開啟使用 bzip2 壓縮的 TAR 檔案進行讀取。
  • w:bz2 − 開啟使用 bzip2 壓縮的 TAR 檔案進行寫入。

使用 Python 建立 tar 檔案

可以使用 Python 中的 tarfile 模組建立 tar 檔案。在以寫入模式開啟檔案後,可以向 tar 檔案中新增更多檔案。

使用 open() 方法

下面是一個使用 open() 方法建立 tar 檔案的 Python 程式碼示例。這裡,我們使用 open() 方法建立一個 tar 檔案。open() 方法的第一個引數接受 "w" 以寫入模式開啟檔案,以及將要生成的 tar 檔案的檔名。

示例

以下是如何使用 open() 方法建立 tar 檔案的示例:

#importing the module import tarfile #declaring the filename name_of_file= "TutorialsPoint.tar" #opening the file in write mode file= tarfile.open(name_of_file,"w") #closing the file file.close()

輸出

輸出結果是建立一個名為“TutorialsPoint”的 tar 檔案。

示例

注意 − 我們可以使用 add() 方法向建立的 tar 檔案中新增檔案。示例如下:

#importing the module import tarfile #declaring the filename name_of_file= "TutorialsPoint.tar" #opening the file in write mode file= tarfile.open(name_of_file,"w") #Adding other files to the tar file file.add("sql python create table.docx") file.add("trial.py") file.add("Programs.txt") #closing the file file.close()

輸出

輸出結果是建立一個名為“TutorialsPoint”的 tar 檔案。要新增的檔名作為輸入傳遞給 add() 方法。

使用 os.listdir() 方法建立和列出檔案

listdir() 方法返回目錄中每個檔案和資料夾的列表。

示例

以下是如何使用 os.listdir() 方法建立 tar 檔案的示例:

import os import tarfile #Creating the tar file File = tarfile.open("TutorialsPoint.tar", 'w') files = os.listdir(".") for x in files: File.add(x) #Listing the files in tar for x in File.getnames(): print ("added the files %s" % x) File.close()

輸出

除了建立 tar 檔案外,我們還會得到以下輸出:

added the files desktop.ini
added the files How to create a tar file using Python.docx
added the files Microsoft Edge.lnk
added the files prateek
added the files prateek/Prateek_Sarika.docx
added the files prateek/sample (no so good just follow the template).docx
added the files untitled.py
added the files ~WRL0811.tmp

在 Python 中使用 tarfile 和 os.walk() 方法建立 tar 歸檔檔案

要從目錄構建 zip 歸檔檔案,請使用 tarfile 模組。使用 os.walk 命令迭代地將目錄樹中的每個檔案新增到其中。

示例

以下是如何建立 tar 歸檔檔案的示例:

import os import tarfile def tardirectory(path,name): with tarfile.open(name, "w:gz") as tarhandle: for root, dirs, files in os.walk(path): for f in files: tarhandle.add(os.path.join(root, f)) tardirectory('C:\Users\Lenovo\Downloads\Work TP','TutorialsPoint.tar.gz') tarfile.close()

輸出

輸出結果是建立一個名為“TutorialsPoint”的 tar 檔案。

更新於:2022年8月18日

13K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.