How to unzip a file with Python 2.4? How to unzip a file with Python 2.4? python python

How to unzip a file with Python 2.4?


You have to use namelist() and extract(). Sample considering directories

import zipfileimport os.pathimport oszfile = zipfile.ZipFile("test.zip")for name in zfile.namelist():  (dirname, filename) = os.path.split(name)  print "Decompressing " + filename + " on " + dirname  if not os.path.exists(dirname):    os.makedirs(dirname)  zfile.extract(name, dirname)


There's some problem with Vinko's answer (at least when I run it). I got:

IOError: [Errno 13] Permission denied: '01org-webapps-countingbeads-422c4e1/'

Here's how to solve it:

# unzip a filedef unzip(path):    zfile = zipfile.ZipFile(path)    for name in zfile.namelist():        (dirname, filename) = os.path.split(name)        if filename == '':            # directory            if not os.path.exists(dirname):                os.mkdir(dirname)        else:            # file            fd = open(name, 'w')            fd.write(zfile.read(name))            fd.close()    zfile.close()


Modifying Ovilia's answer so that you can specify the destination directory as well:

def unzip(zipFilePath, destDir):    zfile = zipfile.ZipFile(zipFilePath)    for name in zfile.namelist():        (dirName, fileName) = os.path.split(name)        if fileName == '':            # directory            newDir = destDir + '/' + dirName            if not os.path.exists(newDir):                os.mkdir(newDir)        else:            # file            fd = open(destDir + '/' + name, 'wb')            fd.write(zfile.read(name))            fd.close()    zfile.close()