The python zipfile module doesn't seem to compress 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() 

The problem is that all my files DO NOT TELL! Files are the same size, and, in fact, only the extension changes to ".zip" (hence the ".xls" in this case).

I am running python 2.5 on winXP sp2.

+48
python compression zipfile
Nov 12 2018-10-12
source share
2 answers

This is because ZipFile requires a compression method. If you do not specify it, it is assumed that the compression method will be zipfile.ZIP_STORED , which saves files only without compressing them. You need to specify the zipfile.ZIP_DEFLATED method. To do this, you need to install the zlib module (usually it is 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() 
+99
Nov 12 '10 at 16:01
source share

There is a very simple way to compress the 'zip file' format,

Use shutil.make_archive in the library.

For example:

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

You can view more extensive documentation at: https://docs.python.org/2/library/shutil.html#shutil.make_archive

+8
Oct 22 '17 at 12:01
source share



All Articles