【问题标题】:Get file names of tarred folder contents in Python在 Python 中获取 tarred 文件夹内容的文件名
【发布时间】:2015-11-12 19:46:44
【问题描述】:

我有一个名为 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 库中。

【问题讨论】:

    标签: python gzip tar


    【解决方案1】:

    对于那个文件,不要使用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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      相关资源
      最近更新 更多