为什么 Python zipfile 不能提供与命令行 zip 相同的输出 .zip 文件大小? [英] Why does Python zipfile not give the same output .zip file size as command-line zip?

查看:18
本文介绍了为什么 Python zipfile 不能提供与命令行 zip 相同的输出 .zip 文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是zip生成的文件大小:

Here is the size of the file generated by zip:

$ seq 10000 > 1.txt 
$ zip 1 1.txt
  adding: 1.txt (deflated 54%)
$ ls -og 1.zip 
-rw-r--r-- 1 22762 Aug 29 10:04 1.zip

这是一个等效的python脚本:

Here is an equivalent python script:

import zipfile
z = zipfile.ZipFile(sys.argv[1], 'w', zipfile.ZIP_DEFLATED)
fn = sys.argv[1]
z.writestr(zipfile.ZipInfo(fn), sys.stdin.read())
z.close()

生成的zip文件大小如下:

The size of the zip file generated is the following:

$ seq 10000 | ./main.py 2.zip 2.txt
$ ls -go 2.zip 
-rw-r--r-- 1 49002 Aug 29 10:15 2.zip

有谁知道为什么python版本生成的zip文件没有zip生成的那么小?

Does anybody know why the python version does not generate the zip file as small as the one generated by zip?

推荐答案

事实证明(在 python 3 中检查)当使用 ZipInfo 时,writestr() 将不使用 zipfile.ZipFile.__init()compressioncompresslevel.这是一个糟糕的 API 设计的例子.应该设计好是否使用ZipInfo,总是使用构造函数中的compressioncompresslevel.

It turns out (checked in python 3) that when ZipInfo is used, writestr() will not use compression and compresslevel of zipfile.ZipFile.__init(). This an example of bad API design. It should have been designed whether ZipInfo is used, compression and compresslevel from the constructor are always used.

将 ZipInfo 实例作为 zinfo_or_arcname 参数传递时,使用的压缩方法将是给定 ZipInfo 实例的 compress_type 成员中指定的压缩方法.默认情况下,ZipInfo 构造函数将此成员设置为 ZIP_STORED.

正因如此,原帖中展示的python代码基本没有压缩.所以python代码生成的文件很大.

Because of this, there is basically no compression in the python code shown on the original post. Therefore, the file size generated by the python code is large.

这个API设计的另一个问题是构造函数中的参数compression.writestr()compress_type相同,但它们是不一样的名字.这是另一个糟糕的设计.没有理由为字面上相同的事物赋予不同的名称.

Another problem of this API design is the parameter compression from the constructor is the same as compress_type of .writestr() but they are not named the same. This is another poor design. There is no reason to give different names for literally the same thing.

这篇关于为什么 Python zipfile 不能提供与命令行 zip 相同的输出 .zip 文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆