获取 Python 中 tar 文件夹内容的文件名

Get file names of tarred folder contents in Python

我有一个名为 gziptest.tar.gz 的压缩文件夹,其中包含几个纯文本文件。

我希望能够获取文件的文件名和相应的内容,但是 gzip 库的使用示例不包括这些。

以下代码:

import gzip
in_f = gzip.open('/home/cholloway/gziptest.tar.gz')
print in_f.read()

产生输出:

gzip test/file2000664 001750 001750 00000000016 12621163624 015761 0ustar00chollowaycholloway000000 000000 I like apples
gzip test/file1000664 001750 001750 00000000025 12621164026 015755 0ustar00chollowaycholloway000000 000000 hello world
line two
gzip test/000775 001750 001750 00000000000 12621164026 015035 5ustar00chollowaycholloway000000 000000 

我可以使用一些正则表达式来检测新文件的开头并提取文件名,但我想知道 gzip 或其他标准 python 库中是否已经存在此功能。

对于该文件,不要使用 gzip 库。使用 tarfile 库。

您正在使用的文件是 test/*.

文件的 tar 存档的 gzip 压缩文件

如果您只想恢复 tar 存档,请使用 gzip 解压缩文件。生成的文件(如您所见)是所需文件的存档。

从逻辑上讲,如果要访问tar存档中的文件,我们必须先使用gzip库恢复tar存档,然后使用tarfile 库来恢复文件。

实际上,我们只使用 tarfile 库:tarfile 库将代表您自动调用 gzip 库。

我从 tarfile 手册页的 the examples section 中复制了这个示例:

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()