30 April 2009

zipfile quirk

In Python 2.6.0, a bug in the zipfile module makes the newly-acquired extractall() method basically useless. The function is supposed to extract all members of a zipfile, "no questions asked", like Windows would do with a right-click "Extract All..."; unfortunately, the original implementation makes it fail when the zipfile contains subdirectories. The behaviour was corrected in one of the 2.6.x maintenance releases (and 3.0.x, and 2.7), but if you have the misfortune to be stuck with 2.6.0, here's the banal workaround:
zf = zipfile.ZipFile(zpath)
zlist = zf.namelist()
for filename in zlist:
 if filename.endswith("/"):
  destpath = os.path.join(path_to_extract,filename[:-1])
  if not os.path.exists(destpath): os.makedirs(destpath)

No comments: