Python zipfile, How to set the compression level?

Question:

Python supports zipping files when zlib is available, ZIP_DEFLATE

see:
https://docs.python.org/3.4/library/zipfile.html

The zip command-line program on Linux supports -1 fastest, -9 best.

Is there a way to set the compression level of a zip file created in Python’s zipfile module?

Asked By: ideasman42

||

Answers:

The zipfile module does not provide this. During compression it uses constant from zlibZ_DEFAULT_COMPRESSION. By default it equals -1. So you can try to change this constant manually, as possible solution.

Answered By: Alex Lisovoy

Starting from python 3.7, the zipfile module added the compresslevel parameter.

https://docs.python.org/3/library/zipfile.html

I know this question is dated, but for people like me, that fall in this question, it may be a better option than the accepted one.

Answered By: Andre Guilhon

Python 3.7+ answer: If you look at the zipfile.ZipFile constructor you’ll see this:

def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True,
             compresslevel=None):
    """Open the ZIP file with mode read 'r', write 'w', exclusive create 'x',
    or append 'a'.
    ...
compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib),
             ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma).
compresslevel: None (default for the given compression type) or an integer
               specifying the level to pass to the compressor.
               When using ZIP_STORED or ZIP_LZMA this keyword has no effect.
               When using ZIP_DEFLATED integers 0 through 9 are accepted.
               When using ZIP_BZIP2 integers 1 through 9 are accepted.
    """

which means you can pass the desired compression in the constructor:

myzip = zipfile.ZipFile(file_handle, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9)

See also https://docs.python.org/3/library/zipfile.html

Answered By: ccpizza
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.