zip file and avoid directory structure

The zipfile.write() method takes an optional arcname argument that specifies what the name of the file should be inside the zipfile

I think you need to do a modification for the destination, otherwise it will duplicate the directory. Use :arcname to avoid it. try like this:

import os
import zipfile

def zip(src, dst):
    zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
    abs_src = os.path.abspath(src)
    for dirname, subdirs, files in os.walk(src):
        for filename in files:
            absname = os.path.abspath(os.path.join(dirname, filename))
            arcname = absname[len(abs_src) + 1:]
            print 'zipping %s as %s' % (os.path.join(dirname, filename),
                                        arcname)
            zf.write(absname, arcname)
    zf.close()

zip("src", "dst")

Leave a Comment