如果安装了zlib,Python支持压缩文件,并使用ZIP_DEFLATE
。
请参阅: https://docs.python.org/3.4/library/zipfile.html
Linux上的zip
命令行程序支持-1
最快,-9
最好的选项。
是否有方法在Python的zipfile
模块中设置zip文件的压缩级别?
如果安装了zlib,Python支持压缩文件,并使用ZIP_DEFLATE
。
请参阅: https://docs.python.org/3.4/library/zipfile.html
Linux上的zip
命令行程序支持-1
最快,-9
最好的选项。
是否有方法在Python的zipfile
模块中设置zip文件的压缩级别?
从Python 3.7开始,zipfile
模块增加了 compresslevel
参数。
https://docs.python.org/3/library/zipfile.html
我知道这个问题的时间比较久远,但对于像我这样的人来说,它可能比已接受的答案更好。
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)
zipfile
模块无法提供此功能。在压缩过程中,它使用zlib
中的常量 - Z_DEFAULT_COMPRESSION
。默认值为-1。因此,您可以尝试手动更改此常量作为可能的解决方案。