I have a problem with compression in Python. I know I should call the ZIP_DEFLATED method when writing to make the zip file compressed, but it does not work for me. I have 3 PDF documents in the C:zip directory. When I run the following code it works just fine:
import os,sys list = os.listdir('C:zip') file = ZipFile('test.zip','w') for item in list: file.write(item) file.close()
It makes the test.zip file without the compression. When I change the fourth row to this:
file = ZipFile('test.zip','w', compression = ZIP_DEFLATED)
It also makes the test.zip file without the compression. I also tried to change the write method to give it the compress_ type argument:
file.write(item, compress_type = ZIP_DEFLATED)
But that doesn’t work either. I use Python version 2.7.4 with Win7. I tired the code with another computer (same circumstances, Win7 and Python 2.7.4), and it made the test.zip file compressed just like it should. I know the zlib module should be available, when I run this:
import zlib
It doesn’t return an error, also if there would be something wrong with the zlib module the code at the top should had return an error too, so I suspect that zlib isn’t the problem.
Advertisement
Answer
By default the ZIP module only store data, to compress it you can do this:
import zipfile try: import zlib mode= zipfile.ZIP_DEFLATED except: mode= zipfile.ZIP_STORED zip= zipfile.ZipFile('zipfilename', 'w', mode) zip.write(item) zip.close()