Master Python Tutorial Zip: The Ultimate Guide to File Compression

Logan Jul 13, 2026

Are you new to Python and eager to dive into practical tasks? Working with compressed files like ZIP archives is an essential skill that can boost your productivity. Today, we're going to guide you through a Python tutorial focusing on the `zipfile` module, which allows you to interact with ZIP archives seamlessly. By the end of this tutorial, you'll be able to create, read, and manipulate ZIP files effortlessly.

a laptop computer sitting on top of a desk next to a plant with the words zip files
a laptop computer sitting on top of a desk next to a plant with the words zip files

Python's `zipfile` module is a robust tool for handling ZIP archives. It provides various classes and methods to create, read, and update ZIP files, making it an invaluable asset for tasks such as data compression, backup, and deployment. In this tutorial, we'll explore the functionalities of the `ZipFile` class and its main methods, enabling you to harness the power of ZIP files in your Python projects.

How to unzip files using Python?
How to unzip files using Python?

Understanding the ZipFile Class

The `ZipFile` class is the cornerstone of the `zipfile` module, enabling you to work with ZIP files as if they were standard file objects. It offers a wide range of methods to create, read, write, and manage ZIP archives. Let's delve into the primary use cases of the `ZipFile` class.

an image of a yellow snake with the words python quick tips
an image of a yellow snake with the words python quick tips

Before diving into the core functionalities, it's essential to import the necessary module and define the file path for the example ZIP archive. Here's how to get started:

```python import zipfile zip_file_path = "example.zip" ```

Creating a New ZIP File

Python Tip: Use zip() Like a Pro 🐍
Python Tip: Use zip() Like a Pro 🐍

The `ZipFile` class can create a new ZIP file using the `open()` method with the 'w' (write) mode. This method returns a `ZipFile` object that you can use to add and manage files within the archive.

To create a new ZIP file named `example.zip`, use the following code snippet:

```python with zipfile.ZipFile(zip_file_path, 'w') as zipf: # Add files and directories to the ZIP archive here ```

With the ZIP file open, you can now add files and directories to the archive using the `write()` method. This method takes two parameters: the file/directory path relative to the ZIP file and the file object to add.

9 Python Loop Tricks Every Beginner Should Learn (Cheat Sheet)
9 Python Loop Tricks Every Beginner Should Learn (Cheat Sheet)

Reading an Existing ZIP File

To read an existing ZIP archive, you can open it with the `open()` method using the 'r' (read) mode. This method returns a `ZipFile` object that you can use to extract files, obtain file information, and perform other read-related tasks.

Let's open an existing ZIP file named `example.zip` for reading:

an image of what is zip function in python?
an image of what is zip function in python?

```python with zipfile.ZipFile(zip_file_path, 'r') as zipf: # Read and extract files from the ZIP archive here ```

Manipulating Files within ZIP Archives

Now that we've explored the basics of creating and reading ZIP files, let's dive into the various methods the `ZipFile` class offers for manipulating files and directories within ZIP archives.

transport of matrix using zip function in python
transport of matrix using zip function in python
Python Cheat Sheet for Beginners
Python Cheat Sheet for Beginners
a black background with white text and an image of a zip logo on the bottom
a black background with white text and an image of a zip logo on the bottom
Stop Writing Loops Like This ❌ (Python Trick 🔥)
Stop Writing Loops Like This ❌ (Python Trick 🔥)
an image of two lists with the text, 2 unzipping lists and 3 random lists
an image of two lists with the text, 2 unzipping lists and 3 random lists
How to Deque in Python?
How to Deque in Python?
a man holding up a poster with the words 5 levels of python on it
a man holding up a poster with the words 5 levels of python on it
Python Projects
Python Projects
5 Python Tricks That Will Save You Hours of Coding
5 Python Tricks That Will Save You Hours of Coding
How to exit Python in the Terminal
How to exit Python in the Terminal
Python's zipapp: Build Executable Zip Applications – Real Python
Python's zipapp: Build Executable Zip Applications – Real Python
"6 Python List Methods Every Beginner Should Know"
"6 Python List Methods Every Beginner Should Know"
Python Projects | Notion
Python Projects | Notion
Master Python in Minutes: Zip & Enumerate Explained! #TechTips #LearnToCode #pythonprogramming
Master Python in Minutes: Zip & Enumerate Explained! #TechTips #LearnToCode #pythonprogramming
How to Print Exception in Python with Examples
How to Print Exception in Python with Examples
Python to_timestamp Easiest Way to Implement with Examples
Python to_timestamp Easiest Way to Implement with Examples
Learn Python Online (2022): 22 Best Python Courses and Tutorials For Beginners
Learn Python Online (2022): 22 Best Python Courses and Tutorials For Beginners
How to Learn Python for Free
How to Learn Python for Free
Python #29: OOPS Basics (Class & Object) | Tutorial by APDaga
Python #29: OOPS Basics (Class & Object) | Tutorial by APDaga

After opening a `ZipFile` object, you can perform the following tasks:

  • Extracting files: Use the `extract()` method to extract files from the ZIP archive to a specified directory. For example: ```python zipf.extract("path/to/file.ext", path=" extraction/directory") ```
  • Listing archive contents: The `namelist()` method returns a list of all files and directories within the ZIP archive.
  • Obtaining file information: You can get detailed information about a file within the ZIP archive using the `getinfo()` method.
  • Closing the ZIP file: The `close()` method saves changes and closes the ZIP file.

Handling Directories within ZIP Archives

In addition to working with individual files, the `ZipFile` class enables you to manage entire directories within ZIP archives. You can add, extract, and manipulate directories using the same methods as files, but with additional considerations. For instance, extracting a directory will also preserve its internal folder structure.

When working with directories, ensure you include the trailing path separator (`\` or `/`) in the file path to maintain the folder hierarchy:

```python zipf.write("path/to/directory/", arcname="folder/name") ```

Practical Examples: Creating and Reading ZIP Archives

Now that we've acquainted ourselves with the `ZipFile` class and its primary functionalities, it's time to put the theory into practice. In this section, we'll create a ZIP archive containing multiple files and directories, and then extract its contents.

First, let's create a new directory structure with some sample files for our example:

```bash mkdir -p example_dir/{sub_dir1,sub_dir2} echo "Sample file 1" > example_dir/file1.txt echo "Sample file 2" > example_dir/file2.txt echo "Sample file 3" > example_dir/sub_dir1/file3.txt ```

Creating a ZIP Archive with Multiple Files and Directories

Now, let's create a new ZIP archive named `example.zip` containing the `example_dir` directory and its contents:

```python import os with zipfile.ZipFile(zip_file_path, 'w') as zipf: # Walk the directory and compress its files for root, _, files in os.walk("example_dir"): for file in files: file_path = os.path.join(root, file) # Add the file to the ZIP archive with its relative path zipf.write(file_path, os.path.relpath(file_path, "example_dir")) ```

Extracting the Contents of a ZIP Archive

Finally, let's extract the contents of the `example.zip` archive to a new directory named `extracted_files`:

```python import shutil # Create a new directory to extract the files shutil.rmtree("extracted_files", ignore_errors=True) shutil.os.makedirs("extracted_files") with zipfile.ZipFile(zip_file_path, 'r') as zipf: # Extract all files to the 'extracted_files' directory zipf.extractall(path="extracted_files") ```

The ZIP archives you create and extract in this tutorial can vary in size and complexity, depending on your project requirements. By mastering the `ZipFile` class and its functionalities, you'll be well-equipped to work with ZIP files in a wide range of Python applications.

Having explored the intricacies of the `zipfile` module and its primary class, the `ZipFile`, you now possess the essential skills to create, read, and manipulate ZIP archives with ease. Embrace the power of Python's built-in libraries to streamline your workflow and boost your productivity. Happy coding!