【问题标题】:How to read gz compressed files from tar如何从 tar 读取 gz 压缩文件
【发布时间】:2017-04-05 07:44:52
【问题描述】:

假设我们有一个 tar 文件,该文件又包含多个 gzip 压缩文件。我希望能够在不压缩 tar 文件或单个 gzip 文件的情况下读取这些 gzip 文件的内容。我正在尝试在 python 中使用tarfile 模块。

【问题讨论】:

    标签: python gzip tarfile


    【解决方案1】:

    这可能行得通,我还没有测试过,但这有主要思想和相关工具。它遍历 tar 中的文件,如果它们被 gzip 压缩,则将它们读入 file_contents 变量:

    import tarfile as t
    import gzip as g 
    for member in t.open("your.gz.tar").getmembers():
        fo=t.extractfile(member)
        file_contents = g.GzipFile(fileobj=fo).read()
    

    注意:如果文件对于内存来说太大,则考虑查看链接的流式阅读器(逐块)。

    如果您有基于成员 (TarInfo) 对象外观的附加逻辑,您可以使用这些:

    见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2014-06-20
      • 2018-09-04
      相关资源
      最近更新 更多