How to unzip a file with Python 2.4?

I'm having a hard time figuring out how to unzip a zip file with 2.4. extract() is not included in 2.4. I'm restricted to using 2.4.4 on my server.

Can someone please provide a simple code example?

-------------Problems Reply------------

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

import zipfile
import os.path
import os
zfile = zipfile.ZipFile("")
for name in zfile.namelist():
(dirname, filename) = os.path.split(name)
print "Decompressing " + filename + " on " + dirname
if not os.path.exists(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 file
def 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):
# file
fd = open(name, 'w')

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):
# file
fd = open(destDir + '/' + name, 'wb')

Not fully tested, but it should be okay:

import os
from zipfile import ZipFile, ZipInfo

class ZipCompat(ZipFile):
def __init__(self, *args, **kwargs):
ZipFile.__init__(self, *args, **kwargs)

def extract(self, member, path=None, pwd=None):
if not isinstance(member, ZipInfo):
member = self.getinfo(member)
if path is None:
path = os.getcwd()
return self._extract_member(member, path)

def extractall(self, path=None, members=None, pwd=None):
if members is None:
members = self.namelist()
for zipinfo in members:
self.extract(zipinfo, path)

def _extract_member(self, member, targetpath):
if (targetpath[-1:] in (os.path.sep, os.path.altsep)
and len(os.path.splitdrive(targetpath)[1]) > 1):
targetpath = targetpath[:-1]
if member.filename[0] == '/':
targetpath = os.path.join(targetpath, member.filename[1:])
targetpath = os.path.join(targetpath, member.filename)
targetpath = os.path.normpath(targetpath)
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
if member.filename[-1] == '/':
if not os.path.isdir(targetpath):
return targetpath
target = file(targetpath, "wb")
return targetpath

I am testing in Python 2.7.3rc2 and the the ZipFile.namelist() is not returning an entry with just the sub directory name for creating a sub directory, but only a list of file names with sub directory, as follows:

['20130923104558/control.json', '20130923104558/test.csv']

Thus the check

if fileName == '':

does not evaluate to True at all.

So I modified the code to check if the dirName exists inside destDir and to create dirName if it does not exist. File is extracted only if fileName part is not empty. So this should take care of the condition where a directory name can appear in ZipFile.namelist()

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

Category:python Views:3 Time:2011-10-18

Related post

  • unraring/unzipping a file using python+django 2011-05-25

    I'm trying to write a distributable web app that will allow the user to upload a compressed archive (rar or zip), extract it on the server side, then do something else with the files. Is there a default library I can hook into to do this? Or is there

  • Removing path from a zip file using python 2011-10-27

    I have a zip file that has a path. When I unzip the file using python and put it in my target folder, it then creates all of the files in the path inside my target folder. Target: d:\unzip_files zip file has a path and file name of: \NIS\TEST\Files\t

  • Unzip part of a file using python gzip module 2009-11-13

    I am trying to unzip a gzipped file in Python using the gzip module. The pre-condition is that, I get 160 bytesof data at a time, and I need to unzip it before I request for the next 160 bytes. Partial unzipping is OK, before requesting the next 160

  • Error in unzipping a file from a python script running as daemon 2010-06-01

    I am getting an error whenever i try to run following unzip command from a python script which is running as a daemon Command : unzip > /dev/null Error End-of-central-directory signature not found$ a zip file, or it constitutes one disk o

  • Unziping files in python 2010-08-10

    I read through the zipfile modules docs, but couldn't understand how to unzip a file, only zip a file. What is the simplest way to unzip all the contents of a zip file into the same directory? --------------Solutions------------- zip_ref = zipfile.Zi

  • Why doesn't my Python 2.6 auto-unzip egg files on import? 2011-09-02

    I'm under the impression that Python import is supposed to automatically unzip egg files in site-packages. My installation doesn't seem to want to auto-unzip the egg. What I tried: (1) I used easy_install to install the suds module, which copied the

  • Create an encrypted ZIP file in Python 2008-08-20

    I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far: import zipfile, os locfile = "test.txt" loczip = os.path.splitext (locfile)[0] + ".zip" zip = zipfile.ZipFile (loczip, "w") zip.write (locfile) zip.close() but I couldn't find h

  • How to find the mime type of a file in python? 2008-09-04

    Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which a

  • extracting text from MS word files in python 2008-09-24

    for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux? Is there any library? --------------Solutions------------- You could make a subprocess call to antiword. Antiword

  • Set permissions on a compressed file in python 2008-11-11

    I have a file test.txt that is inside a zip archive The permissions on test.txt are out of my control when it's compressed, but now I want them to be group-writeable. I am extracting the file with Python, and don't want to escape out to the

  • Unzipping directory structure with python 2009-03-12

    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\\\te

  • How to make an executable file in Python? 2010-04-25

    I want to make an executable file (.exe) of my Python application. I want to know how to do it but have this in mind: I use a C++ DLL! Do I have to put the DLL along side with the .exe or is there some other way? --------------Solutions-------------

  • Reading line by line from a zipped file in python 2011-06-21

    I am trying to read a zipped file in python. I want to read only files with "debug" in their names and only print lines which have BROKER_LOGON in them. It somehow does not read line by line, but prints the entire file which has BROKER_LOGON in it. P

  • How do I read an Excel file into Python using xlrd? Can it read newer Office formats? 2008-09-23

    My issue is below but would be interested comments from anyone with experience with xlrd. I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from a

  • How do I get the modified date/time of a file in Python? 2008-09-23

    This question already has an answer here: How to get file creation & modification date/times in Python? 9 answers How do I get the modified date/time of a file in Python? --------------Solutions------------- os.path.getmtime(filepath) or os.stat(

  • How do I copy a file in python? 2008-09-23

    How do I copy a file in Python? I couldn't find anything under os. --------------Solutions------------- shutil has many methods you can use. One of which is: copyfile(src, dst) Copy the contents of the file named src to a file named dst. The destinat

  • Reading/Writing MS Word files in Python 2008-10-09

    Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object? I know that I can: f = open('c:\file.doc', "w") f.write(text) f.close() but Word will read it as an HTML file not a native .doc file. --------------Solu

  • Removing a sequence of characters from a large binary file using python 2008-10-21

    I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it b

  • Unzipping a file error 2008-12-03

    I am using the SharpZipLib open source .net library from My goal is to unzip an xml file and read it into a dataset. However I get the following error reading the file into a dataset: "Data at the root level is invalid. Line 1, po

Copyright (C), All Rights Reserved.

processed in 0.167 (s). 11 q(s)