Explain Codes LogoExplain Codes Logo

How to get all of the immediate subdirectories in Python

python
directory-listing
file-system
python-stdlib
Nikita BarsukovbyNikita Barsukov·Feb 18, 2025
TLDR

Here's a quick way to get immediate subdirectories:

import os subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]

This leverages os.listdir('.') to cycle through items in the current directory ('.'). It then uses os.path.isdir() to verify if these items are directories, finally returning a list of the subdirectory names.

Harness power of os.scandir() for subdirectory listings

os.listdir() is cool but os.scandir() is where the real deal is at, scoring points in both efficiency and practicality. For large directories, os.scandir() outruns os.listdir(), thanks to its iterator that yields DirEntry objects:

subdirs = [entry.name for entry in os.scandir('.') if entry.is_dir()] # Fast and furious

os.scandir() makes it a breeze to exclude specific directories:

# Those directories that we love to hate excluded_dirs = {'ignore_this', 'and_this'} subdirs = [entry.name for entry in os.scandir('.') if entry.is_dir() and entry.name not in excluded_dirs]

Dir hunting with wildcards using Glob

That wildcard character '*' you've always ignored? It's a beast at pattern matching with glob:

import glob subdirs = glob.glob('*/') # '*/' matches only directories, no files allowed.

Here, the */ pattern signifies interest in only directory-type entities due to the trailing slash.

Walk the directory tree with os.walk()

Deeper tree traversals call for os.walk(). But when you only want immediate subdirectories, add next() to keep it from wandering off.

subdirs = next(os.walk('.'))[1] # Can't walk far with next() holding it back

This command retrieves immediate subdirectories in the current directory, without prying into deeper levels like os.walk() usually does.

Sophisticated dir listing with sorting and pattern matching

Sometimes, order is everything. Sort directories by their modification time or name with the sorted() function:

# Sorting by modification time - because the last modified holds the treasure subdirs = sorted(subdirs, key=lambda d: os.path.getmtime(os.path.join('.', d)))
# Natural name sort – admitted, Ada comes before Bob (duh!) import natsort subdirs = natsort.natsorted(subdirs)

For complex matching or exclusion patterns, glob and fnmatch make a powerful duo:

import fnmatch # Exclude with wildcards - keep pesky temp and backup directories away exclude_patterns = ['temp*', '*.bak'] subdirs = [d for d in os.listdir('.') if os.path.isdir(d) and not any(fnmatch.fnmatch(d, pat) for pat in exclude_patterns)]

Forge powerful scripts with Python's directory tools

Combining all we've learned we can construct robust Python scripts that rule the file system, like this one that does automated file copying:

import shutil def copy_to_subdirs(file, target_dirs): for subdir in target_dirs: shutil.copy(file, os.path.join(subdir, file)) # Call the warriors from any subdir listing method mentioned above subdirs = get_immediate_subdirectories('.') copy_to_subdirs('report.txt', subdirs) # copy-pastes like a lazy intern