文件目录大概是这样:
file.zip
--test
--1.zip
--result.xml
下面是在不解压缩任何文件的情况下读取result.xml第一行内容的代码:
with zipfile.ZipFile(zip_file, 'r') as root_zip:
for name in root_zip.namelist():
if name.endswith("zip"):
zfiledata = BytesIO(root_zip.read(name))
print(name)
with zipfile.ZipFile(zfiledata, 'r') as f:
for file in f.namelist():
if file.endswith("xml"):
print(file)
with f.open(file, 'r') as res:
print(res.readline())
根据文档的解释,zipfile.ZipFile()的file可以是一个类文件对象:
而bytesio可以将字节读取到内存中形成一个类文件对象,这样就可以使用zipfile.ZipFile二次读取获取其中内容.