Alex Rivera | Logout

Unzipping directory structure with python

Asked 2009-03-12T18:44:45.820
30

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?

Edit
Report

2 Answers

7

I know it may be a little late to say this but Jeff is right. It's as simple as:

import os
from zipfile import ZipFile as zip

def extractAll(zipName):
    z = zip(zipName)
    for f in z.namelist():
        if f.endswith('/'):
            os.makedirs(f)
        else:
            z.extract(f)

if __name__ == '__main__':
    zipList = ['one.zip', 'two.zip', 'three.zip']
    for zip in zipList:
        extractAll(zipName)
answered 2011-06-25T14:32:43.357
3

It sounds like you are trying to run unzip to extract the zip.

It would be better to use the python zipfile module, and therefore do the extraction in python.

import zipfile

def extract(zipfilepath, extractiondir):
    zip = zipfile.ZipFile(zipfilepath)
    zip.extractall(path=extractiondir)
answered 2009-03-12T19:03:11.160

Your Answer