How to get all of the immediate subdirectories in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
To get all immediate subdirectories in Python, use pathlib.Path.iterdir() with an is_dir() filter (recommended) or os.listdir() combined with os.path.isdir(). The pathlib approach is the most readable: [p for p in Path(directory).iterdir() if p.is_dir()]. For the os module: [d for d in os.listdir(directory) if os.path.isdir(os.path.join(directory, d))]. Both return only direct children — not nested subdirectories.
pathlib — Recommended Approach
os Module Approach
os.scandir — Faster for Large Directories
os.scandir() is significantly faster than os.listdir() because it reads directory entries without extra stat() calls:
os.walk — Limited to First Level
os.walk() is designed for recursive traversal, but you can take only the first result:
This is concise but less obvious than the iterdir or scandir approaches.
glob Pattern Matching
Filtering Subdirectories
Performance Comparison
For most applications the difference is negligible, but os.scandir() wins on directories with thousands of entries.
Common Pitfalls
os.listdirreturns names, not paths: It returns['src', 'tests'], not full paths. You must join with the parent directory usingos.path.join(directory, name)before callingos.path.isdir(). Passing just the name toisdir()checks relative to the current working directory, which gives wrong results.- Symlinks to directories:
is_dir()andos.path.isdir()follow symlinks by default — a symlink pointing to a directory counts as a directory. To exclude symlinks, addand not p.is_symlink()(pathlib) orand not os.path.islink(path)(os module). - Permission errors on subdirectories:
iterdir()andscandir()can raisePermissionErrorif you lack read permission on the parent directory. Wrap in try/except or checkos.access(directory, os.R_OK)before iterating. - Forgetting hidden directories:
.git,.venv, and.cacheare valid directories that appear in results. If you want only visible directories, explicitly filter out names starting with.. - Using
os.walkwhen you only need one level:os.walk()traverses the entire directory tree. Usingnext(os.walk(directory))stops after the first level but still initializes the full generator. Useiterdir()orscandir()instead for single-level listing.
Summary
- Use
[p for p in Path(dir).iterdir() if p.is_dir()]for clean, readable code (recommended) - Use
os.scandir()for best performance on large directories - Use
next(os.walk(dir))as a quick shortcut but preferiterdirorscandirfor clarity - Always join directory names with the parent path before calling
os.path.isdir() - Filter out hidden directories (
.name.startswith('.')) and__pycache__when needed
Related reading
- How to get all possible 2N combinations of a list’s elements, of any length
- How to get all values from python enum class?
- How to get allocated GPU spec in Google Colab
- How to get an absolute file path in Python
- How to get an absolute file path in Python
- how to get basicproperties header field in pika python from rabbitmq messages?
- How to get contents of a text file from AWS s3 using a lambda function?
- how to get covariance matrix in tensorflow?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.