DEV Community

Paulo GP
Paulo GP

Posted on

Zip and Unzip in Python

Introduction

In the realm of file management, the ability to compress and decompress files and folders is indispensable. Python offers robust functionalities through its zipfile module, empowering developers to zip and unzip with ease. In this article, we'll explore the ins and outs of zipping and unzipping files and folders in Python, illuminating the path to efficient file manipulation.

Index

  • Zipping Files
  • Unzipping Files
  • Zipping Folders
  • Unzipping Folders

Zipping Files

Zipping files in Python is a breeze with the zipfile module. Let's dive into a simple example:

import zipfile

# Create a new zip file
with zipfile.ZipFile(file="example.zip", mode="w") as zip_file:
    zip_file.write(filename="file1.txt")
    zip_file.write(filename="file2.txt")

print("Files zipped successfully!")
Enter fullscreen mode Exit fullscreen mode
Output:
Files zipped successfully!
Enter fullscreen mode Exit fullscreen mode

Unzipping Files

Unzipping files is as straightforward as zipping them. Let's unzip the files we zipped earlier:

import zipfile

# Extract all contents of the zip file
with zipfile.ZipFile(file="example.zip", mode="r") as zip_file:
    zip_file.extractall(path="extracted_files")

print("Files unzipped successfully!")
Enter fullscreen mode Exit fullscreen mode
Output:
Files unzipped successfully!
Enter fullscreen mode Exit fullscreen mode

Zipping Folders

Zipping entire folders proves immensely useful, especially in scenarios involving multiple files. Here's how you can zip a folder:

import zipfile
import os

# Define the folder to zip
folder_to_zip = "folder_to_zip"

# Create a new zip file
with zipfile.ZipFile(file="folder_example.zip", mode="w") as zip_file:
    for folder_name, subfolders, filenames in os.walk(folder_to_zip):
        for filename in filenames:
            file_path = os.path.join(folder_name, filename)
            zip_file.write(file_path, os.path.relpath(file_path, folder_to_zip))

print("Folder zipped successfully!")
Enter fullscreen mode Exit fullscreen mode
Output:
Folder zipped successfully!
Enter fullscreen mode Exit fullscreen mode

Unzipping Folders

Unzipping folders preserves the directory structure, facilitating organized file extraction. Let's unzip the folder we zipped previously:

import zipfile

# Extract all contents of the zip file
with zipfile.ZipFile(file="folder_example.zip", mode="r") as zip_file:
    zip_file.extractall(path="extracted_folder")

print("Folder unzipped successfully!")
Enter fullscreen mode Exit fullscreen mode
Output:
Folder unzipped successfully!
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, Python's zipfile module empowers developers to zip and unzip files and folders effortlessly. Whether you're compressing individual files or entire directories, Python provides a seamless experience, enabling efficient file management.

Top comments (0)