How to list only top-level directories in Python
Codemia Knowledge Hub ·
Read the immediate entries of the directory and keep only the ones that are directories. With pathlib that is [e for e in Path(base).iterdir() if e.is_dir()]. No recursive walk is needed.
pathlib.iterdir()
pathlib is usually the most readable option in modern Python.
This lists only the directories directly inside /tmp. Files are ignored, and nothing below those directories is traversed. For plain strings instead of Path objects, use str(directory), or directory.name for just the final component.
os.scandir()
os.scandir is also a strong choice, especially when performance matters.
Each entry already carries file-type metadata, so the directory check is cheaper than joining paths and calling a separate stat for each name, which is what os.listdir() plus a per-name check ends up doing.
One level of os.walk()
os.walk is built for recursive traversal, so it is more than you need here. If you use it anyway, the first yielded tuple holds the top-level subdirectory names:
It works, but pathlib.iterdir() or os.scandir() states the intent more directly.
Hidden directories, symlinks and sorting
Depending on the use case, you may want to:
- skip hidden directories whose names start with a dot
- include or exclude symlinks deliberately, since linked directories can produce surprising output
- sort the results for stable output
A filtered pathlib version:
That is often enough for scripts, build tools and filesystem inspection.
Handling missing paths and permission errors
The call fails if the path does not exist or the process lacks permission. Wrap it when the path is user-supplied or external:
For controlled internal paths you can keep the code simpler, but for tools and utilities this makes the behavior much more predictable.
Related reading
- How to load a model from an HDF5 file in Keras?
- How to load a pickle file from S3 to use in AWS Lambda?
- How to load a tflite model in script?
- How to load a tsv file into a Pandas DataFrame?
- How to load all modules in a folder?
- How to load an image and show the image using keras?
- How to load tfjs model into python using keras/tensorflow
- How to load/edit/run/save text files .py into an IPython notebook cell?
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.