代码之家  ›  专栏  ›  技术社区  ›  user3684314

在Python3中将gzip与多个文件一起使用

  •  1
  • user3684314  · 技术社区  · 8 年前

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

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

    这个档案中有数百个文件。。。那么基本上 gzip 在Python3中,包可以与多个文件一起使用吗?我只对一个压缩文件使用过它,所以我不知道如何浏览多个文件或多个级别的“压缩”。

    我通常的减压方法是:

    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()
    

    使用的主要包装是 gzip , tarfile 和 xml.etree.ElementTree .

    2 回复  |  直到 8 年前
        1
  •  1
  •   tripleee    8 年前

    gzip 仅支持压缩单个文件或流。在您的例子中,exrtacted流是一个 tar 对象,所以可以使用Python的 tarfile library 操作提取的内容。这个图书馆其实知道如何应对 .tar.gz 所以不需要显式地提取 gzip 你自己

        2
  •  0
  •   Mark Adler    8 年前

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