Skip to content
Advertisement

Is there any method to compress ZIP files in python?

I have tried creating zip using zipfile and shutil. But, there was not visible file size compression in both the methods.

zipfile

with zipfile.ZipFile(f'{directory_name}.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:

shutil

shutil.make_archive(directory_path, 'zip', directory_path)

Is there any way to ensure file compression as well?

Thanks.

Advertisement

Answer

You did

with zipfile.ZipFile(f'{directory_name}.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:

zipfile.ZipFile docs state

The compresslevel parameter controls the compression level to use when writing files to the archive. When using ZIP_STORED or ZIP_LZMA it has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information).

Please try different compresslevel i.e.

with zipfile.ZipFile(f'{directory_name}.zip', 'w', zipfile.ZIP_DEFLATED, compresslevel=0) as zipf:

to

with zipfile.ZipFile(f'{directory_name}.zip', 'w', zipfile.ZIP_DEFLATED, compresslevel=9) as zipf:

then check if it does affect size of created file

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement