Python
Directories
File System
Coding Tips
Programming Guide

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.

python
1from pathlib import Path
2
3base = Path("/tmp")
4subdirs = [entry for entry in base.iterdir() if entry.is_dir()]
5
6for directory in subdirs:
7    print(directory.name)

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.

python
1import os
2
3base = "/tmp"
4subdirs = [entry.name for entry in os.scandir(base) if entry.is_dir()]
5print(subdirs)

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:

python
1import os
2
3base = "/tmp"
4root, dirnames, filenames = next(os.walk(base))
5print(dirnames)

It works, but pathlib.iterdir() or os.scandir() states the intent more directly.

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:

python
1from pathlib import Path
2
3base = Path("/tmp")
4subdirs = sorted(
5    entry.name
6    for entry in base.iterdir()
7    if entry.is_dir() and not entry.name.startswith(".")
8)
9
10print(subdirs)

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:

python
1from pathlib import Path
2
3try:
4    base = Path("/does/not/exist")
5    subdirs = [entry.name for entry in base.iterdir() if entry.is_dir()]
6    print(subdirs)
7except FileNotFoundError:
8    print("Path does not exist")
9except PermissionError:
10    print("Permission denied")

For controlled internal paths you can keep the code simpler, but for tools and utilities this makes the behavior much more predictable.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Data 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.

Practice algorithms