您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何从Python的zip文件中的zip文件读取?

如何从Python的zip文件中的zip文件读取?

当您.open()ZipFile实例上使用调用时,您确实会得到一个打开的文件句柄。但是,要 读取 zip文件ZipFile该类需要更多内容。它需要能够在该文件上进行 搜索 ,并且.open()在您的情况下,返回的对象是不可搜索的。只有Python 3(3.2及更高版本)会生成ZipExFile支持搜索的对象(前提是外部zip文件的基础文件句柄是可搜索的,并且没有任何尝试写入该ZipFile对象的操作)。

解决方法是读取整个拉链进入使用存储器.read(),其存储在一个BytesIO对象(一个内存文件 搜索)和进料,为了ZipFile

from io import BytesIO

# ...
        zfiledata = BytesIO(zfile.read(name))
        with zipfile.ZipFile(zfiledata) as zfile2:

或者,在您的示例中:

import zipfile
from io import BytesIO

with zipfile.ZipFile("parent.zip", "r") as zfile:
    for name in zfile.namelist():
        if re.search(r'\.zip$', name) is not None:
            # We have a zip within a zip
            zfiledata = BytesIO(zfile.read(name))
            with zipfile.ZipFile(zfiledata) as zfile2:
                for name2 in zfile2.namelist():
                    # Now we can extract
                    logging.info( "Found internal internal file: " + name2)
                    print "Processing code goes here"
python 2022/1/1 18:28:12 有196人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶