Python zipfile – Add files to an existing ZIP file

In this post we will be creating a Python script that will add files to an existing 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 add an additional file to an existing zip file. We begin with a with statement to open the ZIP archive in append mode (“a”). The script then writes the file “file.pdf” to the zip file, using the ‘write()’ method. This adds our new file to the root directory of the zip file.

import zipfile

with zipfile.ZipFile("", "a") as zip_ref:

Tip: Ensure your zip file is closed when running the above code sample.

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply