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.

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Imagine monitoring actually built for developers

Billboard image

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay