Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Display all the directories in a directory
In Python, we can use the pathlib module, os module, and glob module to display all the directories within a directory. The os module contains various functions like os.scandir(), os.walk(), os.listdir(), and glob methods like glob() and iglob() to list all directories in a specified path.
Method 1: Using the Pathlib Module
The pathlib module provides an object-oriented approach to handle file system paths. We can use Path.iterdir() to get path objects of directory contents and filter directories using is_dir().
Syntax
Path('directory_path').iterdir()
Example
This example shows how to list all directories in the current working directory ?
from pathlib import Path
import os
# Create some sample directories for demonstration
os.makedirs('sample_dir/subdir1', exist_ok=True)
os.makedirs('sample_dir/subdir2', exist_ok=True)
os.makedirs('sample_dir/subdir3', exist_ok=True)
# Create a file to show it's filtered out
with open('sample_dir/sample_file.txt', 'w') as f:
f.write('Sample file')
# List all directories
root_path = Path('sample_dir')
print("Directories found:")
for path in root_path.iterdir():
if path.is_dir():
print(path)
Directories found: sample_dir/subdir1 sample_dir/subdir2 sample_dir/subdir3
Method 2: Using the OS Module
Using os.listdir() Method
The os.listdir() method returns all contents of a directory, requiring additional filtering to get only directories ?
import os
# List all directories using os.listdir()
path = "sample_dir"
all_items = os.listdir(path)
print("All items in directory:")
print(all_items)
print("\nDirectories only:")
for item in all_items:
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
print(item)
All items in directory: ['sample_file.txt', 'subdir1', 'subdir2', 'subdir3'] Directories only: subdir1 subdir2 subdir3
Using os.scandir() Method
The os.scandir() method is more efficient than os.listdir() as it returns directory entries with built-in methods to check file types ?
import os
# Using os.scandir() to list directories
path = "sample_dir"
print("Directories using os.scandir():")
with os.scandir(path) as entries:
for entry in entries:
if entry.is_dir():
print(entry.name)
Directories using os.scandir(): subdir1 subdir2 subdir3
Using os.walk() Method
The os.walk() method recursively traverses directory trees, useful for finding directories at all levels ?
import os
# Create nested directories for demonstration
os.makedirs('sample_dir/subdir1/nested1', exist_ok=True)
os.makedirs('sample_dir/subdir2/nested2', exist_ok=True)
# Using os.walk() to find all directories recursively
path = "sample_dir"
print("All directories (recursive):")
for root, dirs, files in os.walk(path):
level = root.replace(path, '').count(os.sep)
indent = ' ' * 2 * level
print(f"{indent}{os.path.basename(root)}/")
# Print subdirectories
subindent = ' ' * 2 * (level + 1)
for directory in dirs:
print(f"{subindent}{directory}/")
All directories (recursive):
sample_dir/
subdir1/
nested1/
subdir2/
nested2/
subdir3/
Method 3: Using the Glob Module
Using glob.glob() Method
The glob module uses pattern matching to find directories. Use the */ pattern to match directories specifically ?
import glob
# Using glob to find directories with pattern matching
path = "sample_dir"
print("Directories using glob pattern '*/':")
directories = glob.glob(f"{path}/*/")
for directory in directories:
print(directory)
print("\nDirectories using glob pattern (without trailing slash):")
all_items = glob.glob(f"{path}/*")
for item in all_items:
if os.path.isdir(item):
print(item)
Directories using glob pattern '*/': sample_dir/subdir1/ sample_dir/subdir2/ sample_dir/subdir3/ Directories using glob pattern (without trailing slash): sample_dir/subdir1 sample_dir/subdir2 sample_dir/subdir3
Comparison
| Method | Performance | Recursive | Pattern Support | Best For |
|---|---|---|---|---|
pathlib.Path |
Good | No | No | Modern Python, object-oriented approach |
os.listdir() |
Good | No | No | Simple directory listing |
os.scandir() |
Best | No | No | Performance-critical applications |
os.walk() |
Moderate | Yes | No | Recursive directory traversal |
glob.glob() |
Good | Optional | Yes | Pattern-based directory matching |
Conclusion
Use os.scandir() for best performance, pathlib for modern object-oriented code, and os.walk() for recursive directory traversal. Choose glob when you need pattern matching capabilities.
