Get the List of all empty Directories in Python

When working with file systems and directories in Python, it's often useful to identify and handle empty directories. Empty directories can accumulate over time, taking up unnecessary space or cluttering the directory structure. Being able to programmatically find and handle these empty directories can help streamline file system operations and improve overall organization.

In this tutorial, we will explore different methods to obtain a list of all empty directories using Python. We will cover two approaches: the first using the os.walk() function, and the second utilizing the os.scandir() function.

Method 1: Using os.walk()

The os.walk() function is a powerful tool for traversing directories in Python. It allows us to iterate through a directory tree and access all the directories and files within it. By combining it with other functions from the os module, we can easily identify empty directories.

How os.walk() Works

The os.walk() function takes a starting directory path as input and generates a generator that yields a tuple of three values for each directory: the directory path, a list of subdirectories, and a list of filenames.

Example

Let's create a complete example that finds empty directories ?

import os
import tempfile

# Create a temporary directory structure for demonstration
with tempfile.TemporaryDirectory() as temp_dir:
    # Create some directories and files
    os.makedirs(os.path.join(temp_dir, "folder1", "subfolder1"))
    os.makedirs(os.path.join(temp_dir, "folder2"))  # This will be empty
    os.makedirs(os.path.join(temp_dir, "folder3", "subfolder2"))
    
    # Create a file in folder1
    with open(os.path.join(temp_dir, "folder1", "file1.txt"), "w") as f:
        f.write("Hello World")
    
    def get_empty_directories(path):
        empty_dirs = []
        for dirpath, dirnames, filenames in os.walk(path):
            if not dirnames and not filenames:
                empty_dirs.append(dirpath)
        return empty_dirs
    
    # Find empty directories
    empty_directories = get_empty_directories(temp_dir)
    print("Empty directories found:")
    for directory in empty_directories:
        print(directory)
Empty directories found:
/tmp/tmp_directory/folder2
/tmp/tmp_directory/folder1/subfolder1
/tmp/tmp_directory/folder3/subfolder2

In this example, we check if both dirnames and filenames lists are empty. If they are, we add the directory path to our results list.

Method 2: Using os.scandir()

Starting from Python 3.5, the os.scandir() function was introduced as a more efficient alternative to os.listdir(). It provides better performance when accessing file attributes.

Example

Here's how to find empty directories using os.scandir() ?

import os
import tempfile

def get_empty_directories_scandir(path):
    empty_dirs = []
    
    def is_directory_empty(dir_path):
        try:
            with os.scandir(dir_path) as entries:
                return not any(True for _ in entries)
        except PermissionError:
            return False
    
    def scan_recursive(current_path):
        try:
            with os.scandir(current_path) as entries:
                for entry in entries:
                    if entry.is_dir():
                        if is_directory_empty(entry.path):
                            empty_dirs.append(entry.path)
                        else:
                            # Recursively scan subdirectories
                            scan_recursive(entry.path)
        except PermissionError:
            pass
    
    scan_recursive(path)
    return empty_dirs

# Create a test directory structure
with tempfile.TemporaryDirectory() as temp_dir:
    # Create directories and files
    os.makedirs(os.path.join(temp_dir, "data", "empty_folder"))
    os.makedirs(os.path.join(temp_dir, "docs"))
    os.makedirs(os.path.join(temp_dir, "src", "utils"))
    
    # Create a file in src directory
    with open(os.path.join(temp_dir, "src", "main.py"), "w") as f:
        f.write("print('Hello')")
    
    # Find empty directories
    empty_dirs = get_empty_directories_scandir(temp_dir)
    print("Empty directories found:")
    for directory in empty_dirs:
        print(directory)
Empty directories found:
/tmp/tmp_directory/data/empty_folder
/tmp/tmp_directory/docs
/tmp/tmp_directory/src/utils

The os.scandir() method offers improved performance compared to os.listdir() due to its ability to return file attribute information more efficiently.

Comparison

Method Performance Recursion Best For
os.walk() Good Built-in Simple directory traversal
os.scandir() Better Manual implementation Large directory structures

Conclusion

Both methods effectively find empty directories in Python. Use os.walk() for simple cases with built-in recursion, or os.scandir() for better performance with large directory structures. Consider adding error handling for permission issues when working with system directories.

Updated on: 2026-03-27T12:26:40+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements