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

前端 未结 2 770
名媛妹妹
名媛妹妹 2020-12-08 06:18

I made a little helper function:

import zipfile

def main(archive_list=[],zfilename=\'default.zip\'):
    print zfilename
    zout = zipfile.ZipFile(zfilenam         


        
相关标签:
2条回答
  • 2020-12-08 06:36

    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()  
    
    0 讨论(0)
  • 2020-12-08 06:45

    There is a really easy way to compress zip format,

    Use in shutil.make_archive library.

    For example:

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

    Can see more extensive documentation at: Here

    0 讨论(0)
提交回复
热议问题