如何使用 Python 创建 tar 文件?
磁带存档文件是 tar 文件中的字母 TAR 所代表的意思。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 文件。