Extract a specific file from a zip archive without maintaining directory structure in python

淺唱寂寞╮ 提交于 2019-11-29 11:04:22

问题


I'm trying to extract a specific file from a zip archive using python.

In this case, extract an apk's icon from the apk itself.

I am currently using

with zipfile.ZipFile('/path/to/my_file.apk') as z:
    # extract /res/drawable/icon.png from apk to /temp/...
    z.extract('/res/drawable/icon.png', 'temp/')

which does work, in my script directory it's creating temp/res/drawable/icon.png which is temp plus the same path as the file is inside the apk.

What I actually want is to end up with temp/icon.png.

Is there any way of doing this directly with a zip command, or do I need to extract, then move the file, then remove the directories manually?


回答1:


You can use zipfile.ZipFile.open:

import os
import shutil

with zipfile.ZipFile('/path/to/my_file.apk') as z:
    with z.open('/res/drawable/icon.png') as zf, open('temp/icon.png', 'wb') as f:
        shutil.copyfileobj(zf, f)

Or use zipfile.ZipFile.read:

import os

with zipfile.ZipFile('/path/to/my_file.apk') as z:
    with open('temp/icon.png', 'wb') as f:
        f.write(z.read('/res/drawable/icon.png'))


来源:https://stackoverflow.com/questions/17729703/extract-a-specific-file-from-a-zip-archive-without-maintaining-directory-structu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!