Compress a directory tree in Python with zipfile

Trying to compress a folder with the Python module zipfile results in an IOError exception being thrown. To overcome this simply combine os.walk with arcname argument of zipfile.write:


Z = zipfile.ZipFile('teste.zip', 'w')
for r, d, f in os.walk('teste'):
  for ff in f:
    Z.write(os.path.join(r, ff), os.path.join(r, ff))
Z.close()