17

Doing something like this:

from zipfile import ZipFile

#open zip file
zipfile = ZipFile('Photo.zip')

#iterate zip contents
for zipinfo in zipfile.filelist:
    #do something
    filepath, filename = path.split(zipinfo.filename)

How do I know if zipinfo is a file or a directory?

Dharman
  • 30,962
  • 25
  • 85
  • 135
neurino
  • 11,500
  • 2
  • 40
  • 63

2 Answers2

17

Probably this is the right way:

is_dir = lambda zipinfo: zipinfo.filename.endswith('/')
neurino
  • 11,500
  • 2
  • 40
  • 63
  • 2
    I believe the directory separator is always normalised to `/` within a zip file, no matter which platform is was created on. – Greg Hewgill Jan 19 '12 at 23:24
  • @Greg: my doubt was it was dependent by the platform the zip was **opened** but have no Windows box to test it. – neurino Jan 20 '12 at 08:08
  • No, there is no change. The path separator inside a zip file is always `/` no matter which platform it's opened on. – Greg Hewgill Jan 22 '12 at 20:31
  • 1
    FYI, in zip files found in the wild, there will not always be a directory member where there are files inside that directory. Sometimes only the file members will exist, without a separate member for the containing directory. – amoe Mar 19 '16 at 03:22
  • Oh, what a crock this module is. If you print() a ZipInfo, it shows a "filemode". There's no such member. – Jürgen A. Erhard Jun 13 '16 at 00:46
13

Starting with Python 3.6 there is a ZipInfo.is_dir() method.

with zipfile.ZipFile(zip_file) as archive:
    for file in archive.namelist():
        file_info = archive.getinfo(file)
        if file_info.is_dir():
            # do something

See the Python 3.6 docs for details.

Markus Hi
  • 1,709
  • 18
  • 19