In this post we will be creating a Python script that will create a new zip file. To achieve this we will utilize the Python zipfile module. The zipfile module in Python provides tools for working with ZIP archive files, including creating, reading, and modifying them. It allows users to compress, decompress, add, and extract files and folders from ZIP archives, making it a useful module for managing ZIP archives in Python.
See the snippet of Python code below where we use the zipfile module to create a new zip file and add files to it. We utilize a with statement to create a new zip file named ‘Folder.zip’. Here we also enable the write mode (‘w’), which allows us to add new files. Using the ‘write()’ method we add the file “file.pdf” to the ZIP archive.
import zipfile with zipfile.ZipFile("Folder.zip", "a") as zip_ref: zip_ref.write("file.pdf")
In the example above we add only one file although this can be changed to add multiple, for example.
import zipfile with zipfile.ZipFile("Folder.zip", "a") as zip_ref: zip_ref.write("file.pdf") zip_ref.write("file1.txt") zip_ref.write("file2.pdf")
Take a look at some of our other content around the Python programming language by clicking here.