Snorlax
Snorlax

Reputation: 827

efficiently zipping files using python

I need to zip directories:

directory -> directory.zip.

It should be possible to easily open that file on WIndows but creation of that file should be as fast as possible -> sth like tar

Then original directory may be deleted. What would be the best options for that? The only reason for "zipping" that directory is to be able to download it over http as one file.

Upvotes: 0

Views: 100

Answers (2)

WhatsThePoint
WhatsThePoint

Reputation: 3635

For zipping directories I have always used the zipfile module, and used it like so;

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()

Then called with this;

zip(str(source), str(destination))

Upvotes: 1

Thomas
Thomas

Reputation: 181745

You can use the built-in zipfile module. In particular ZIP_STORED disables compression.

For extra performance, you could also send the generated zip output directly into the HTTP response, without first creating a file on disk or a buffer in memory.

Upvotes: 1

Related Questions