1

I am trying to zip some files present in a directory. Zipping is done successfully, but size doesn't seem to compress a lot.

My code :

import os
import zipfile
import sys
def zipdir(client, path):
    os.chdir(path)
    if client == 'ABC':
        zipf = zipfile.ZipFile('Store.zip', 'w')
        zipf.write('Facts.txt')
        for f in os.listdir(path):
            if f.endswith('.txt') or f.endswith('.xls'):
                if 'pretty' in f:
                    zipf.write(f)
        zipf.close()

When I try to zip it in unix shell script, the size becomes 40M. But When I try to zip it in Python, size is 196M

Any suggestions ?

Marvin
  • 421
  • 1
  • 5
  • 15
  • 2
    Possible duplicate: see http://stackoverflow.com/questions/4166447/python-zipfile-module-doesnt-seem-to-be-compressing-my-files – Dan-Dev May 15 '17 at 14:26
  • 1
    You just have to supply the compression parameter ZIP_STORED or ZIP_DEFLATED. https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile – gnub May 15 '17 at 14:26
  • 3
    Possible duplicate of [python zipfile module doesn't seem to be compressing my files](http://stackoverflow.com/questions/4166447/python-zipfile-module-doesnt-seem-to-be-compressing-my-files) – Aaron May 15 '17 at 14:27
  • Thanks everybody. That helped. Seems like i could have searched some more ;) – Marvin May 15 '17 at 14:31

1 Answers1

4

You have to specify the compression when making the zipfile.ZipFile

ZipFile constructor

class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True)

ZIP_STORED is uncompressed:

The numeric constant for an uncompressed archive member.

so you will have to change that to one of these

compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA;

Context manager

And it's better to work with a context manager (with) which automatically opens and closes the file, also when something goes wrong

so you can change that portion to something like

with zipfile.ZipFile('Store.zip', 'w', compression=zipfile.ZIP_LZMA) as zipf
    zipf.write('Facts.txt')
    for f in os.listdir(path):
        if f.endswith('.txt') or f.endswith('.xls'):
            if 'pretty' in f:
                zipf.write(f)

depending on the chosen compression algorithm

Maarten Fabré
  • 6,938
  • 1
  • 17
  • 36