DEV Community

abbazs
abbazs

Posted on • Edited on

7 2

How to unzip multiple zip files in a folder using python?

Tutorial: Extracting Zip Files

In this tutorial, we will learn how to extract all the Zip files in a directory using Python's zipfile module and the pathlib module. We'll go through the code step by step and discuss different ways to encapsulate this functionality in a function.

Code Explanation

import zipfile
from pathlib import Path

# Set the target directory
p = Path('.')

# Iterate over all Zip files in the directory
for f in p.glob('*.zip'):
    # Open the Zip file
    with zipfile.ZipFile(f, 'r') as archive:
        # Extract all contents of the Zip file to a directory with the same name as the file
        archive.extractall(path=f'./{f.stem}')
        # Print a message indicating that the extraction is complete
        print(f"Extracted contents from '{f.name}' to '{f.stem}' directory.")
Enter fullscreen mode Exit fullscreen mode

The code performs the following steps:

  1. Import the necessary modules: zipfile for working with Zip files and pathlib for working with file paths.

  2. Create a Path object to represent the current directory. You can modify this to specify a different directory if needed.

  3. Use the glob method of the Path object to iterate over all the Zip files (*.zip) in the current directory.

  4. For each Zip file, open it using zipfile.ZipFile in read mode ('r').

  5. Use the extractall method of the Zip file object to extract all the contents of the Zip file to a directory with the same name as the file. The path=f'./{f.stem}' argument specifies the destination directory.

  6. After the extraction is complete, print a message indicating that the process is done, using print(f"Extracted contents from '{f.name}' to '{f.stem}' directory.").

Recipe 1: Function with Directory Parameter

import zipfile
from pathlib import Path

def extract_zip_files(directory):
    p = Path(directory)
    for f in p.glob('*.zip'):
        with zipfile.ZipFile(f, 'r') as archive:
            archive.extractall(path=f'./{f.stem}')
            print(f"Extracted contents from '{f.name}' to '{f.stem}' directory.")

# Usage example
extract_zip_files('.')
Enter fullscreen mode Exit fullscreen mode

This recipe demonstrates creating a function extract_zip_files that accepts a directory parameter. It performs the same functionality as the previous code but allows you to specify a different directory.

Recipe 2: Function with Output Path

import zipfile
from pathlib import Path

def extract_zip_files(directory, output_path):
    p = Path(directory)
    for f in p.glob('*.zip'):
        with zipfile.ZipFile(f, 'r') as archive:
            archive.extractall(path=output_path)
            print(f"Extracted contents from '{f.name}' to '{output_path}' directory.")

# Usage example
extract_zip_files('.', './extracted_files')
Enter fullscreen mode Exit fullscreen mode

This recipe demonstrates creating a function extract_zip_files that accepts both a directory parameter and an output_path parameter. It allows you to specify a custom output directory where the extracted files will be stored.

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

Top comments (0)

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay