从 zip 存档中提取特定文件,而无需在 python 中维护目录结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17729703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:01:20  来源:igfitidea点击:

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

pythonzipdirectory-structure

提问by rcbevans

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

我正在尝试使用 python 从 zip 存档中提取特定文件。

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

在这种情况下,从 apk 本身提取 apk 的图标。

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.pngwhich is temp plus the same path as the file is inside the apk.

这确实有效,在我的脚本目录中,它正在创建temp/res/drawable/icon.png临时加上与文件在 apk 内的路径相同的路径。

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

我真正想要的是以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?

有没有办法直接使用 zip 命令执行此操作,或者我是否需要提取,然后移动文件,然后手动删除目录?

采纳答案by falsetru

You can use zipfile.ZipFile.open:

您可以使用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:

或者使用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'))