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

时间:2014-12-17 12:57:00

标签: python zip zlib

Python支持在zlib可用时压缩文件,ZIP_DEFLATE

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

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

有没有办法设置在Python zipfile模块中创建的zip文件的压缩级别?

3 个答案:

答案 0 :(得分:5)

zipfile模块不提供此功能。在压缩期间,它使用来自zlib - Z_DEFAULT_COMPRESSION的常量。默认情况下,它等于-1。因此,您可以尝试手动更改此常量,作为可能的解决方案。

答案 1 :(得分:4)

从python 3.7 zipfile开始,添加了compresslevel参数。 (https://docs.python.org/3/library/zipfile.html

我知道这个问题已经过时,但是对于像我这样的人来说,这个问题可能比公认的更好。

答案 2 :(得分:0)

Python3答案:如果您查看zipfile.ZipFile构造函数,您将看到以下内容:

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

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(TESTFN2, "w", compression=zipfile.ZIP_STORED)

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

相关问题