Monday, January 4, 2010

Python's Zipfile library

So you want to generate a big bundle of files all at once, and send 'em in one convenient package? Python's ZipFile library to the rescue! You can create each file, write it to a zip, then send the whole mess over the wire without ever touching the disk! (StringIO is pretty essential as well.)

Ahh, but wait: anyone unzipping your files will find each file marked unreadable/unwritable/unexecutable. And the Python ZipFile docs have zilch to say about it.

This turns out to be the requisite incantation, care of Stackoverflow:

info = zipfile.ZipInfo(name)
info.external_attr = 0777 << 16
zip.writestr(info, bytes)

Obvious, no? Of COURSE you need to bitshift the permissions by 16! (File perms clearly occupy the first 16b of an int, which might even be the standard on Unix, but that doesn't excuse the Python docs' utter silence on the matter.)

1 comment:

Alex said...
This comment has been removed by a blog administrator.