How To Zip Files In Python

Pavol Kutaj
1 min readApr 26, 2022

--

The aim of this pageđź“ťis to guide you through the creation of a compressed zip file by using the default zipfile module in Python (there are many other modules for compressing into other formats, of course)

1. STEPS

  • important: by default, the module only stores and does not compress, this has to be explicitly set
  • using this for small files (deployment logs) and therefore opting for the highest compression levels (performance considerations are a non-issue for me)
  • to sum this, you need 4 args
  • file_name.zip
  • mode="w"
  • compression method=ZIP_DEFLATED
  • compression_level=9
  • the bare-boned syntax you can test from the python REPL would be (I am compressing README.txt →example.zip)
from zipfile import ZIP_DEFLATED, ZipFile as zip
with zip("example.zip", mode="w",compression=ZIP_DEFLATED,compresslevel=9) as archive:
archive.write("README.txt")

2. EXAMPLE

  • the example is a particular function from a script that automates deployments and compresses output.txt into a filename containing information about a particular deployment (Jira card, deployed component, git user name of a deployer, timestamp) and also automatically pushes that to GitHub

3. LINKS

--

--

No responses yet