Python zipfile module does not compress files

I have a compression problem in Python. I know that when writing, I have to call the ZIP_DEFLATED method to make a compressed zip file, 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 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 compression. When I change the fourth line to this:

 file = ZipFile('test.zip','w', compression = ZIP_DEFLATED) 

It also makes the test.zip file without compression. I also tried changing the write method to give it the compress_ type argument:

 file.write(item, compress_type = ZIP_DEFLATED) 

But that doesn't work either. I am using Python version 2.7.4 with Win7. I was tired of the code with another computer (the same circumstances, Win7 and Python 2.7.4), and it made the test.zip file compressed as it should. I know that the zlib module should be available when I run this:

 import zlib 

It does not return an error, also if something is wrong in the zlib module, the code above should also return an error, so I suspect that zlib is not a problem.

+4
source share
1 answer

By default, the ZIP module only saves 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() 
+10
source

Source: https://habr.com/ru/post/1496196/


All Articles