Python zipfile,如何设置压缩级别?

16

如果安装了zlib,Python支持压缩文件,并使用ZIP_DEFLATE

请参阅: https://docs.python.org/3.4/library/zipfile.html

Linux上的zip命令行程序支持-1最快,-9最好的选项。

是否有方法在Python的zipfile模块中设置zip文件的压缩级别?


1
目前尚未实现,参见:http://bugs.python.org/issue21417 - jedie
3个回答

25

从Python 3.7开始,zipfile 模块增加了 compresslevel 参数。

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

我知道这个问题的时间比较久远,但对于像我这样的人来说,它可能比已接受的答案更好。


8

Python 3.7+ 的答案: 如果你查看 zipfile.ZipFile 文件文档,你会看到:

""" 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.

"""

这意味着您可以在构造函数中传递所需的压缩方式:

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

另请参阅https://docs.python.org/3/library/zipfile.html


7

zipfile模块无法提供此功能。在压缩过程中,它使用zlib中的常量 - Z_DEFAULT_COMPRESSION。默认值为-1。因此,您可以尝试手动更改此常量作为可能的解决方案。


1
不是很好(或线程安全),但这似乎是唯一的方法。 - ideasman42
1
“Z_DEFAULT_COMPRESSION代表速度和压缩之间的默认折衷(当前等同于级别6)。”-- Python 3.6文档。因此,这不是一个坏的默认值。 - Tritium21

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接