Welcome, guest | Sign In | My Account | Store | Cart

Python can work directly with data in zip files. You can look at the list of items in the directory and work with the data files themselves.

Python, 7 lines
1
2
3
4
5
6
7
import zipfile

z = zipfile.ZipFile("zipfile.zip", "rb")
for filename in z.namelist():
        print filename
        bytes = z.read(filename)
        print len(bytes)

The ZipFile module does not currently handle ZIP files which have appended comments, or multi-disk ZIP files.

4 comments

Michael Keller 22 years, 9 months ago  # | flag

mode incorrect? The sample threw an exception on my box.

Traceback (most recent call last):
  File "tryzipfile.py", line 3, in ?
    z = zipfile.ZipFile("zipfile.zip", "rb")
  File "c:\python21\lib\zipfile.py", line 167, in __init__
    self.fp = open(file, modeDict[mode])
KeyError: rb

Changing the mode to:

z = zipfile.ZipFile("zipfile.zip", "r")

works ok.

Ahsan A 22 years, 7 months ago  # | flag

Which platform. You are on Unix/Linux I'll bet.

the 'b' is for mac or windows platforms.

Steve Borrok 22 years, 4 months ago  # | flag

Which platform. I am running on Windows 2000 and recieve the exception with mode "rb". Everything worked fine with mode "r".

Joel Lawhead 22 years ago  # | flag

Exception confirmation. I was able to recreate the exception as well on Windows 2000 using ActivePython 2.1.1, build 212 (ActiveState). Changing 'rb' to 'r' worked.