如何在不维护Python目录结构的情况下从zip中提取文件? [英] How to extract file from zip without maintaining directory structure in Python?
问题描述
我正尝试使用python从zip存档中提取特定文件。
I'm trying to extract a specific file from a zip archive using python.
在这种情况下,请从apk本身提取apk的图标。
In this case, extract an apk's icon from the apk itself.
我当前正在使用
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/')
这确实有效,在我的脚本目录中正在创建 temp / res / drawable / icon.png
是temp加上与文件在apk内相同的路径。
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.
我实际上想要得到的最终结果是 temp / icon.png
。
What I actually want is to end up with temp/icon.png
.
有没有办法直接使用zip命令,还是我需要解压缩,然后移动文件,然后手动删除目录?
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?
推荐答案
您可以使用< a href = http://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.open rel = nofollow noreferrer> zipfile.ZipFile.ope n :
import shutil
import zipfile
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)
或使用 zipfile.ZipFile.read :
import zipfile
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'))
这篇关于如何在不维护Python目录结构的情况下从zip中提取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!