by: Cobena Isaac

How to Automatically Unzip Files into Their Own Folders with Python

How to Automatically Unzip Files into Their Own Folders with Python

Working with multiple compressed archives can be tedious—manually extracting each one, creating folders, and cleaning up.If you have a folder full of .zip files, like downloaded datasets, software packages, or document bundles — unzipping each one manually can be a real time sink.

In this tutorial, you’ll learn how to use Python to automatically extract every .zip file in a directory into its own folder — all in just a few lines of code.

You’ll need Python installed on your system. If you don’t have it, you can download it from python.org. We’ll be using built-in Python modules, so no extra installations are required.

Example :

Suppose, you have a directory full of .zip files that need to be extracted into individual folders. Manually doing this for dozens of files is time-consuming and error-prone.

Solution

You’ll write a python script that:

  • Scans a directory for .zip files,
  • Creates a new folder for each archive, and
  • Extracts the contents into their respective folders automatically.
  • Optionally deletes the original zip files to reduce clutter.

For example, dataset1.zip will be extracted into a folder called dataset1/.

Complete Script

Create a new file called unzip_all.py or any other .py file and paste this code in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import os
import zipfile
import shutil

def unzip_all_in_folder(directory_path, delete_zip_after_extraction = False):
    """
    Scans a directory for .zip files and extracts each into a new folder
    named after the zip file.

    Args:
        directory_path (str): The path to the directory containing zip files.
        delete_zip_after_extraction (bool): If True, deletes the original
                                            zip file after successful extraction.
    """
    print(f"Scanning directory: {directory_path} for .zip files...")

    # Iterate through all items in the specified directory
    for item in os.listdir(directory_path):
        item_path = os.path.join(directory_path, item)

        # Check if it's a file and has a .zip extension
        if os.path.isfile(item_path) and item.lower().endswith('.zip'):
            zip_file_name = item
            
            # Create a destination folder named after the zip file (without .zip extension)
            folder_name = os.path.splitext(zip_file_name)[0]
            destination_folder = os.path.join(directory_path, folder_name)

            # Create the destination folder if it doesn't exist
            os.makedirs(destination_folder, exist_ok=True)

            try:
                print(f"\nFound '{zip_file_name}'. Extracting to '{folder_name}/'...")
                # Extract the zip file
                with zipfile.ZipFile(item_path, 'r') as zip_ref:
                    zip_ref.extractall(destination_folder)

                print(f"Successfully extracted '{zip_file_name}' to '{destination_folder}'")
                
                # Optional: Delete original zip file
                if delete_zip_after_extraction:
                    os.remove(item_path)
                    print(f"Deleted original zip file: '{zip_file_name}'")

            except zipfile.BadZipFile:
                print(f"Error: '{zip_file_name}' is not a valid zip file. Skipping.")

                # Clean up the created folder if extraction failed due to bad zip
                if os.path.exists(destination_folder) and not os.listdir(destination_folder):
                    os.rmdir(destination_folder)

            except Exception as e:
                print(f"An unexpected error occurred while processing '{zip_file_name}': {e}")
                
                # Clean up the created folder if extraction failed
                if os.path.exists(destination_folder) and not os.listdir(destination_folder):
                    os.rmdir(destination_folder)

        elif os.path.isdir(item_path):
            print(f"Skipping directory: '{item}'")
        else:
            print(f"Skipping non-zip file: '{item}'")

    print("\nZip file processing complete!")

if __name__ == "__main__":
    # Test with a sample directory first!

    # Example: A subfolder in your home directory named "my_downloads"
    target_directory = os.path.expanduser("~/my_downloads")  # Change this path

    # Uncomment the line below and replace with a test directory for safe testing
    # target_directory = "/path/to/your/test/zip_folder"

    # Set to True if you want to delete the original zip files after extraction
    delete_originals = False  # Safer to keep as False initially

    unzip_all_in_folder(target_directory, delete_zip_after_extraction=delete_originals)

Let’s break down the key parts of the script.

1. Importing Modules

1
import os, zipfile, shutil

Here is what what the modules do:

  • os — module provides functions for interacting with the operating system, like listing directory contents (os.listdir), joining paths (os.path.join), creating directories (os.makedirs), and deleting files (os.remove).
  • zipfile — is Python’s built-in module for working with ZIP archives. It allows us to open, read, write, and extract contents from .zip files.
  • shutil — optional cleanup or folder removal

2. File Identification

1
2
3
4
5
for item in os.listdir(directory_path):
    item_path = os.path.join(directory_path, item)

    if os.path.isfile(item_path) and item.lower().endswith('.zip'):
        # ... process zip file ...

We loop through the folder contents and check if each item is a .zip file.

The :

  • os.listdir(directory_path) — gets a list of all files and folders in the specified directory_path.
  • os.path.isfile(item_path) — checks if the current item is a file (not a directory).
  • item.lower().endswith(‘.zip’) — checks if the file name ends with .zip (case-insensitive) to identify our target archives.

The script checks each item in your directory, processing only actual files (not folders) that have the .zip extension.

3. Folder Creation

1
2
3
4
5
zip_file_name = item
folder_name = os.path.splitext(zip_file_name)[0]
destination_folder = os.path.join(directory_path, folder_name)

os.makedirs(destination_folder, exist_ok=True)

How the parts work:

  • os.path.splitext(zip_file_name)[0] — is a neat trick to get the file name without its extension. For my_archive.zip, it returns my_archive. This will be our new folder’s name.
  • os.makedirs(destination_folder, exist_ok = True) — creates the new folder (e.g., my_archive) where the contents will be extracted. exist_ok = True prevents an error if a folder with that name already exists.

Each .zip file gets its own subfolder, named after the file (minus .zip). For example: for my_archive.zip, this creates a folder called my_archive in the same directory.

4. Archive Extraction

1
2
with zipfile.ZipFile(item_path, 'r') as zip_ref:
    zip_ref.extractall(destination_folder)

This extracts all the contents of the archive into the new folder.

  • zipfile.ZipFile(item_path, ‘r’) — Opens the .zip file in read mode ('r'). The with statement ensures the file is properly closed even if errors occur.
  • zip_ref.extractall(destination_folder) — This is the core command that extracts all contents of the .zip archive into the specified destination_folder.

5. (Optional) Deletion of Original Zip

1
2
if delete_zip_after_extraction:
    os.remove(item_path)

After successful extraction, the original zip file can be automatically deleted to save space. For example, if the delete_zip_after_extraction flag is set to True, this line will remove the original .zip file after its contents have been successfully extracted, helping keep your directory clean.

Before and After Example

Your folder before running the script:

1
2
3
4
5
downloads/
├── project_docs.zip
├── dataset_files.zip
├── photos_archive.zip
└── readme.txt

Your folder after after running the script:

1
2
3
4
5
6
7
8
9
10
11
downloads/
├── project_docs/
   ├── manual.pdf
   └── specifications.docx
├── dataset_files/
   ├── data.csv
   └── metadata.json
├── photos_archive/
   ├── image1.jpg
   └── image2.png
├── readme.txt
Run the Script
  1. Save the script as unzipper.py
  2. (Optional) Set delete_originals to False for testing
  3. Open your terminal or command prompt.
  4. Navigate to the directory where you saved your script using the cd command.

    1
    
    cd /path/to/your/script
    
  5. Run the script:
    1
    
    python unzipper.py
    

You’ll see output in your terminal indicating which zip files are being processed.

1
2
3
4
📁 Scanning directory: /Users/peter/my_downloads
🗜️ Extracting 'project_data.zip'  'project_data/'
 Done: project_data.zip
🎉 All zip files processed!

Remember: Always try scripts like this in a test folder before running them on important files, and consider keeping delete_originals = False if you want to keep the original zip files.

Wrap-Up

You now have a simple automation tool (a handy Python script) that can instantly extract multiple .zip archives into clean, well-organized folders — no manual work required.

In just a few lines of code, you’ve built a mini automation tool that can:

  • Find all .zip files in a folder
  • Extract each into its own subfolder
  • Optionally delete the originals

This little script can save you hours when dealing with large data extraction task, many compressed files, Kaggle datasets, or downloads cleanup. Just remember to always test automation scripts on non-critical data first!

Hope you found this tutorial useful!.

Additional Resources

The following tutorials explain how to perform other common file-handling tasks in Python: