在 Python 3 中使用带有多个文件的 gzip 存档

问题描述 投票:0回答:2

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

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

主要使用的软件包是

gzip
tarfile
xml.etree.ElementTree

python python-3.x character-encoding gzip compression
2个回答
4
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.