Well that's odd. Python's zipfile defaults to the stored compression method, which does not compress! (Why would they do that?)
You need to specify a compression method. Use ZIP_DEFLATED, which is the most widely supported.
import zipfile
zip = zipfile.ZipFile("stuff.zip", "w", zipfile.ZIP_DEFLATED)
zip.write("test.txt")
zip.close()
Answer from Mark Adler on Stack OverflowVideos
Well that's odd. Python's zipfile defaults to the stored compression method, which does not compress! (Why would they do that?)
You need to specify a compression method. Use ZIP_DEFLATED, which is the most widely supported.
import zipfile
zip = zipfile.ZipFile("stuff.zip", "w", zipfile.ZIP_DEFLATED)
zip.write("test.txt")
zip.close()
From the https://docs.python.org/3/library/zipfile.html#zipfile-objects it suggest example:
with ZipFile('spam.zip', 'w') as myzip:
myzip.write('eggs.txt')
So your code will be
from zipfile import ZipFile
with ZipFile('compressedtextstuff.zip', 'w', zipfile.ZIP_DEFLATED) as myzip:
myzip.write('testtext.txt')
The easiest way is to use shutil.make_archive. It supports both zip and tar formats.
import shutil
shutil.make_archive(output_filename, 'zip', dir_name)
If you need to do something more complicated than zipping the whole directory (such as skipping certain files), then you'll need to dig into the zipfile module as others have suggested.
As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code:
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, '..')))
with zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
zipdir('tmp/', zipf)