【问题标题】:how to extract members of tar.gz file within a zip file in Python如何在 Python 的 zip 文件中提取 tar.gz 文件的成员
【发布时间】:2020-08-02 02:58:25
【问题描述】:

zip 文件包含 tar.gz 文件。如何在不先提取到磁盘的情况下检索 tar.gz 文件的成员?

abc.zip
  |- def.txt
  |- ghi.zip 
  |- jkl.tar.gz


def scan_zip_file(zfile):
    l_files = []
    with zipfile.ZipFile(zfile, 'r') as zf:
        for zname in zf.namelist(): 
            if zname.endswith('.zip'):
                with zipfile.ZipFile(io.BytesIO(zf.read(zname))) as zf2:
                   l_files.extend(zf2.namelist())
            elif zname.endswith('.tar.gz'):
                pass
            else:
                l_files.append(zname)

【问题讨论】:

  • 您发布的代码有什么问题?它的输出与您的预期有何不同?
  • 还想从 tar.gz 中检索成员...不仅是 zip

标签: python zipfile tarfile


【解决方案1】:

您可以使用tarfile 模块,方式与使用 zipfile 模块非常相似。 完成代码并获取 tar.gz 文件中的文件名:

def scan_zip_file(zfile):
    l_files = []
    with zipfile.ZipFile(zfile, 'r') as zf:
        for zname in zf.namelist(): 
            if zname.endswith('.zip'):
                with zipfile.ZipFile(io.BytesIO(zf.read(zname))) as zf2:
                   l_files.extend(zf2.namelist())
            elif zname.endswith('.tar.gz'):
                with tarfile.open(fileobj=io.BytesIO(zf.read(zname))) as tf:
                   l_files.extend(tf.getnames())
            else:
                l_files.append(zname)

tarfile.openfileobj 参数告诉它使用 io.BytesIO 返回的“类文件对象”。

【讨论】:

  • tarfile.open(io.BytesIO(zf.read(zname))) 给出异常:“expected str, bytes or os.PathLike object, not _io.BytesIO”
  • @fivelements 你忘记了 fileobj 参数
  • 编辑答案以添加有关 fileobj 的信息
猜你喜欢
  • 2016-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2016-09-25
相关资源
最近更新 更多