Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract file from zip without maintaining directory structure in Python?

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?

like image 213
rcbevans Avatar asked Jul 18 '13 16:07

rcbevans


People also ask

How do I extract a single file from a zip file?

Do one of the following: To unzip a single file or folder, open the zipped folder, then drag the file or folder from the zipped folder to a new location. To unzip all the contents of the zipped folder, press and hold (or right-click) the folder, select Extract All, and then follow the instructions.

How do I extract all zip files from a directory in Python?

To unzip a file in Python, use the ZipFile. extractall() method. The extractall() method takes a path, members, pwd as an argument and extracts all the contents. To work on zip files using Python, we will use an inbuilt python module called zipfile.


1 Answers

You can use zipfile.ZipFile.open:

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) 

Or use 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')) 
like image 110
falsetru Avatar answered Oct 20 '22 07:10

falsetru