python zipfile模块似乎没有压缩我的文件 [英] python zipfile module doesn't seem to be compressing my files
问题描述
我做了一个小帮手函数:
I made a little helper function:
import zipfile
def main(archive_list=[],zfilename='default.zip'):
print zfilename
zout = zipfile.ZipFile(zfilename, "w")
for fname in archive_list:
print "writing: ", fname
zout.write(fname)
zout.close()
if __name__ == '__main__':
main()
问题是我的所有文件都没有压缩!文件大小相同,实际上只是将扩展名更改为.zip(在本例中为.xls)。
The problem is that all my files are NOT being COMPRESSED! The files are the same size and, effectively, just the extension is being change to ".zip" (from ".xls" in this case).
在winXP sp2上运行python 2.5。
I'm running python 2.5 on winXP sp2.
推荐答案
这是因为 ZipFile
您可以指定压缩方法。如果不指定它,它假设压缩方法为 zipfile.ZIP_STORED
,它只存储文件而不压缩它们。您需要将方法指定为 zipfile.ZIP_DEFLATED
。您需要为此安装 zlib
模块(默认情况下通常安装)。
This is because ZipFile
requires you to specify the compression method. If you don't specify it, it assumes the compression method to be zipfile.ZIP_STORED
, which only stores the files without compressing them. You need to specify the method to be zipfile.ZIP_DEFLATED
. You will need to have the zlib
module installed for this (it is usually installed by default).
import zipfile
def main(archive_list=[],zfilename='default.zip'):
print zfilename
zout = zipfile.ZipFile(zfilename, "w", zipfile.ZIP_DEFLATED) # <--- this is the change you need to make
for fname in archive_list:
print "writing: ", fname
zout.write(fname)
zout.close()
if __name__ == '__main__':
main()
这篇关于python zipfile模块似乎没有压缩我的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!