Check if Directory Contains Any Other Directory in Python



In Python, when we are working with directory structures, it is necessary to check whether a given directory contains any other directories within it or not. This process of checking is useful when performing batch operations, cleaning up folders, or traversing file systems. Python provides several built-in ways to perform this check effectively.

In this article, we will go through different methods using both os and pathlib modules to determine if a directory contains any subdirectories.

Using os.listdir() and os.path.isdir()

The os.listdir() method is the straightforward method to detect subdirectories to list directory contents, and when it is combined with os.path.isdir() method we can verify if an item is a directory or not.

Example

This example uses a generator expression to quickly check if an item is a directory or at least a subdirectory:

import os

# Define the target directory
directory = r'D:\Tutorialspoint'

# Check if any item is a directory
has_subdirs = any(os.path.isdir(os.path.join(directory, item)) for item in os.listdir(directory))

# Output result
print("Contains subdirectories" if has_subdirs else "No subdirectories found.")

Here is the output of the above program:

Contains subdirectories

Using os.scandir()

The os.scandir() method is a more efficient alternative introduced in Python 3.5. It provides file attributes without additional calls by making it faster when working with large directories.

Example

In this example, we are using the os.scandir() method to check for subdirectories:

import os

# Define the target directory
directory = r'D:\Tutorialspoint'

# Use os.scandir for efficient directory scanning
with os.scandir(directory) as entries:
    has_subdirs = any(entry.is_dir() for entry in entries)

# Output result
print("Contains subdirectories" if has_subdirs else "No subdirectories found.")

Following is the output of the above program:

Contains subdirectories

Using pathlib.Path.iterdir()

The pathlib module provides an object-oriented interface to filesystem paths. The Path.iterdir() method provides a way to iterate over directory contents and check for directories using the .is_dir() method.

Example

Following is an example that shows how to use the path.iterdir() method of the pathlib module to check if the subdirectories are present:

from pathlib import Path

# Define the target directory
directory = Path(r'D:\Tutorialspoint')

# Check if the directory has subdirectories
has_subdirs = any(item.is_dir() for item in directory.iterdir())

# Output result
print("Contains subdirectories" if has_subdirs else "No subdirectories found.")

Below is the output of the above program:

Contains subdirectories
Updated on: 2025-05-15T15:56:48+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements