当您
.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 zipfilefrom io import BytesIOwith 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 pre goes here"


