I have a zip file which contains the following directory structure:
dir1\dir2\dir3a dir1\dir2\dir3b
I'm trying to unzip it and maintain the directory structure however I get the error:
IOError: [Errno 2] No such file or directory: 'C:\\\projects\\\testFolder\\\subdir\\\unzip.exe'
where testFolder is dir1 above and subdir is dir2.
Is there a quick way of unzipping the file and maintaining the directory structure?
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.
We create a ZipFile object in READ mode and name it as zip. printdir() method prints a table of contents for the archive. extractall() method will extract all the contents of the zip file to the current working directory. You can also call extract() method to extract any file by specifying its path in the zip file.
The extract and extractall methods are great if you're on Python 2.6. I have to use Python 2.5 for now, so I just need to create the directories if they don't exist. You can get a listing of directories with the namelist()
method. The directories will always end with a forward slash (even on Windows) e.g.,
import os, zipfile z = zipfile.ZipFile('myfile.zip') for f in z.namelist(): if f.endswith('/'): os.makedirs(f)
You probably don't want to do it exactly like that (i.e., you'd probably want to extract the contents of the zip file as you iterate over the namelist), but you get the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With