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?
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.