【问题标题】:Use gzip with archive with multiple files in Python 3在 Python 3 中将 gzip 与包含多个文件的存档一起使用
【发布时间】:2018-11-13 02:13:21
【问题描述】:

所以基本上我有一个这样的文件系统:

main_archive.tar.gz
  main_archive.tar
    sub_archive.xml.gz
      actual_file.xml

这个存档中有数百个文件...所以基本上,gzip 包可以与 Python 3 中的多个文件一起使用吗?我只将它与一个压缩文件一起使用,所以我不知道如何遍历多个文件或多个级别的“压缩”。

我常用的解压方法是:

with gzip.open(file_path, "rb") as f:
  for ln in f.readlines():
    *decode encoding here*

当然,这有很多问题,因为通常“f”只是一个文件……但现在我不确定它代表什么?

任何帮助/建议将不胜感激!

编辑 1:

我已经接受了下面的答案,但是如果您正在寻找类似的代码,我的主干基本上是:

tar = tarfile.open(file_path, mode="r")
for member in tar.getmembers():
    f = tar.extractfile(member)
    if verbose:
        print("Decoding", member.name, "...")
    with gzip.open(f, "rb") as temp:
        decoded = temp.read().decode("UTF-8")
        e = xml.etree.ElementTree.parse(decoded).getroot()
        for child in e:
            print(child.tag)
            print(child.attrib)
            print("\n\n")

tar.close()

使用的主要包是gziptarfilexml.etree.ElementTree

【问题讨论】:

    标签: python python-3.x character-encoding gzip compression


    【解决方案1】:

    gzip 仅支持压缩单个文件或流。在您的情况下,提取的流是 tar 对象,因此您可以使用 Python 的 tarfile library 来操作提取的内容。这个库实际上知道如何处理.tar.gz,所以你不需要自己显式提取gzip

    【讨论】:

    【解决方案2】:

    使用 Python 的 tarfile 来获取包含的文件,然后在循环中再次使用 Python 的 gzip 来提取 xml。

    【讨论】:

      猜你喜欢
      • 2015-01-28
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      相关资源
      最近更新 更多