如何在不维护Python目录结构的情况下从zip中提取文件?
我正尝试使用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?
您可以使用 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'))