add empty directory using zipfile?

Tung Wai Yip tungwaiyip at yahoo.com
Thu Jun 26 23:39:11 CEST 2003


On Thu, 26 Jun 2003 03:40:01 -0400, Oren Tirosh
<oren-py-l at hishome.net> wrote:

>On Thu, Jun 26, 2003 at 04:31:37AM +0000, JanC wrote:
>> Tung Wai Yip <tungwaiyip at yahoo.com> schreef:
>> 
>> > Can I add empty directory using zipfile? When I try to add a directory
>> > it complains that it is not a file.
>> 
>> ZIP files can't contain directories, only files and the paths to those 
>> files.  A workaround might be to put an empty file in the directory.
>
>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 
>zipfile.py 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 zipfile.py.
>
>    Oren

I reverse engineered a zip file. Looks like I can save an empty
directory by setting zipinfo.external_attr as 48 (at least for Windows
2000).

  z = zipfile.ZipFile("new.zip","w")
  zinfo = zipfile.ZipInfo("empty/",(2002,12,31,23,59,59))
  zinfo.external_attr = 48
  z.writestr(zinfo, "")

I guess zipfile should be enhanced to save empty directory too.

Wai Yip Tung





More information about the Python-list mailing list