python解压zip_用python解压嵌套的zip文件

这是我想出的一个函数。def extract_nested_zipfile(path, parent_zip=None):

"""Returns a ZipFile specified by path, even if the path contains

intermediary ZipFiles. For example, /root/gparent.zip/parent.zip/child.zip

will return a ZipFile that represents child.zip

"""

def extract_inner_zipfile(parent_zip, child_zip_path):

"""Returns a ZipFile specified by child_zip_path that exists inside

parent_zip.

"""

memory_zip = StringIO()

memory_zip.write(parent_zip.open(child_zip_path).read())

return zipfile.ZipFile(memory_zip)

if ('.zip' + os.sep) in path:

(parent_zip_path, child_zip_path) = os.path.relpath(path).split(

'.zip' + os.sep, 1)

parent_zip_path += '.zip'

if not parent_zip:

# This is the top-level, so read from disk

parent_zip = zipfile.ZipFile(parent_zip_path)

else:

# We're already in a zip, so pull it out and recurse

parent_zip = extract_inner_zipfile(parent_zip, parent_zip_path)

return extract_nested_zipfile(child_zip_path, parent_zip)

else:

if parent_zip:

return extract_inner_zipfile(parent_zip, path)

else:

# If there is no nesting, it's easy!

return zipfile.ZipFile(path)

我是这样测试的:echo hello world > hi.txt

zip wrap1.zip hi.txt

zip wrap2.zip wrap1.zip

zip wrap3.zip wrap2.zip

print extract_nested_zipfile('/Users/mattfaus/dev/dev-git/wrap1.zip').open('hi.txt').read()

print extract_nested_zipfile('/Users/mattfaus/dev/dev-git/wrap2.zip/wrap1.zip').open('hi.txt').read()

print extract_nested_zipfile('/Users/mattfaus/dev/dev-git/wrap3.zip/wrap2.zip/wrap1.zip').open('hi.txt').read()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值