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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:35:39  来源:igfitidea点击:

python zipfile module doesn't seem to be compressing my files

pythoncompressionzipfile

提问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()  

回答by Gavriel Cohen

There is a really easy way to compress zipformat,

有一种非常简单的方法来压缩 zip格式,

Use in shutil.make_archivelibrary.

shutil.make_archive图书馆使用。

For example:

例如:

import shutil

shutil.make_archive(file_name, 'zip', file location after compression)

Can see more extensive documentation at: Here

可以在以下位置查看更广泛的文档:此处