16

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?

ideasman42
  • 42,413
  • 44
  • 197
  • 320

3 Answers3

25

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.

jftuga
  • 1,913
  • 5
  • 26
  • 49
Andre Guilhon
  • 378
  • 4
  • 9
8

Python 3.7+ answer: If you look at the zipfile.ZipFile docs you'll see:

""" Class with methods to open, read, write, close, list zip files.

z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True,
            compresslevel=None)

file: Either the path to the file, or a file-like object.
      If it is a path, the file will be opened and closed by ZipFile.
mode: The mode can be either 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).
allowZip64: if True ZipFile will create files with ZIP64 extensions when
            needed, otherwise it will raise an exception when this would
            be necessary.
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

ccpizza
  • 28,968
  • 18
  • 162
  • 169
7

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

Alex Lisovoy
  • 5,767
  • 3
  • 27
  • 28
  • 1
    Not so nice (or threadsafe). but this seems to be the only way. – ideasman42 Jan 24 '15 at 02:44
  • 1
    "Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6)." -- python 3.6 docs. so its not a bad default – Tritium21 Jun 02 '17 at 14:52