如何使用 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() 方法
下面顯示了一個建立 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 檔案被建立。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP