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.
Zipfile
constructor says "IfZIP_DEFLATED
is specified but the zlib module is not available,RuntimeError
is also raised." So if you don't get an error it should work. Note, it's not necessary to specify acompress_type
keyword argument on awrite()
call unless you want to override the value given for thecompression
parameter to the constructor. – Packton