add empty directory using zipfile?

JanC usenet_spam at janc.invalid
Thu Jun 26 22:19:49 CEST 2003

Oren Tirosh <oren-py-l at> schreef:

> ZIP files *can* contain directories. They are described as zero-length
> files with some flag set.  I don't see any specific API for this in 
> but I think that if you pass a ZipInfo record with the right
> values to ZipFile.writestr it should probably work. Consult the 
> documentation of the zip format or just create a zip containing an empty 
> directory with any zip utility look at the ZipInfo using

I checked with some Windows ZIP utilities and it seems like they don't add 
empty directories--oh wait it's an option that's off by default...
( *oops* ;)

They are added as an empty "file", with a filename sometimes ending in "/"  
and sometimes not (this is not defined in the ZIP format specs?), and the 
"directory" external attribute set.

The following script works for me:
import zipfile

zf = zipfile.ZipFile('', 'w')

# This works:
zfi = zipfile.ZipInfo('test1/')
zf.writestr(zfi, '')

# This works too:
zfi = zipfile.ZipInfo('test2')
zfi.external_attr = 16
zf.writestr(zfi, '')

# But this doesn't:
# zf.write('test3')
# And this doesn't either:
# zf.write('test4/')


Seems like the zipfile module requires the trailing "/" and/or manual 
setting the attribute for directories in the ZipInfo object.  If you want 
to preserve other attributes you'll have to set them manually...

And the write() method doesn't work with directories...  :-(
In fact the write() method is broken and doesn't store any file attributes 
correctly on Windows...


"Be strict when sending and tolerant when receiving."
RFC 1958 - Architectural Principles of the Internet - section 3.9

More information about the Python-list mailing list