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

ide*_*n42 4 python zip zlib

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

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

zipLinux上的命令行程序支持-1最快,-9最好.

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

ccp*_*zza 9

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.

"""
Run Code Online (Sandbox Code Playgroud)

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

myzip = zipfile.ZipFile(file_handle, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9)
Run Code Online (Sandbox Code Playgroud)

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


小智 7

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

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


Ale*_*voy 5

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

  • “Z_DEFAULT_COMPRESSION 表示速度和压缩之间的默认折衷(当前相当于级别 6)。” -- python 3.6 文档。所以它是一个不错的默认值 (2认同)