python zipfile 模块似乎没有压缩我的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4166447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python zipfile module doesn't seem to be compressing my files
提问by Ramy
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()
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).
问题是我所有的文件都没有被压缩!文件大小相同,实际上只是将扩展名更改为“.zip”(在本例中为“.xls”)。
I'm running python 2.5 on winXP sp2.
我在 winXP sp2 上运行 python 2.5。
采纳答案by Chinmay Kanchi
This is because ZipFilerequires 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 zlibmodule installed for this (it is usuallyinstalled by default).
这是因为ZipFile需要您指定压缩方法。如果你不指定它,它假定压缩方法是zipfile.ZIP_STORED,它只存储文件而不压缩它们。您需要指定要使用的方法zipfile.ZIP_DEFLATED。您需要为此zlib安装模块(通常默认安装)。
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()

