Python
directory management
file navigation
subdirectory handling
os module

Python list directory, subdirectory, and files

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Python gives you several good ways to list directories and files, and the best one depends on whether you want a flat listing or a recursive walk. For new code, pathlib is usually the clearest API, while os.walk remains a strong choice when you want explicit control over directory traversal.

The key is to decide early whether you need names, full paths, only files, only directories, or a complete recursive tree. Once that is clear, the implementation becomes simple.

Use pathlib for a Flat Listing

For modern Python code, pathlib.Path is often the most readable option.

python
1from pathlib import Path
2
3root = Path(".")
4
5for entry in root.iterdir():
6    if entry.is_dir():
7        print("DIR ", entry)
8    else:
9        print("FILE", entry)

iterdir() lists the immediate contents of one directory. It does not recurse into subdirectories.

You can also separate files and directories easily:

python
1from pathlib import Path
2
3root = Path(".")
4files = [p for p in root.iterdir() if p.is_file()]
5directories = [p for p in root.iterdir() if p.is_dir()]
6
7print(files)
8print(directories)

Use os.walk for Recursive Traversal

If you need to visit a directory tree recursively, os.walk is the classic tool.

python
1import os
2
3for dirpath, dirnames, filenames in os.walk("."):
4    print("Directory:", dirpath)
5    print("  Subdirectories:", dirnames)
6    print("  Files:", filenames)

This is useful because each iteration already gives you the current directory, the subdirectories under it, and the files in it. You do not need to call isfile or isdir manually for every entry just to understand the tree structure.

Recursive Listing with pathlib

If you like pathlib, you can still recurse with rglob.

python
1from pathlib import Path
2
3root = Path(".")
4
5for path in root.rglob("*"):
6    if path.is_dir():
7        print("DIR ", path)
8    else:
9        print("FILE", path)

This is concise and works well for many scripts. It is especially convenient when you also want pattern matching, such as only listing Python files.

python
1from pathlib import Path
2
3for path in Path(".").rglob("*.py"):
4    print(path)

Build Full Paths Correctly

A common beginner mistake is to call os.listdir and then forget that it returns only entry names, not full paths.

python
1import os
2
3entries = os.listdir(".")
4for name in entries:
5    full_path = os.path.join(".", name)
6    print(full_path)

If you need full paths often, pathlib avoids this problem because each item is already a Path object that knows its own location.

If the goal is to display the structure clearly, combine recursion with indentation.

python
1from pathlib import Path
2
3def print_tree(path: Path, indent: int = 0) -> None:
4    for entry in sorted(path.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower())):
5        print("  " * indent + entry.name)
6        if entry.is_dir():
7            print_tree(entry, indent + 1)
8
9print_tree(Path("."))

This is useful for quick diagnostics, CLI tools, and file-audit scripts.

Choose the Right Tool

A practical rule is:

  • use Path.iterdir() for one directory
  • use os.walk() for structured recursive traversal
  • use Path.rglob() for recursive pattern-based searches

There is no need to force one API into every situation. The right answer depends on how much control and filtering you need.

Common Pitfalls

  • Using os.listdir() and forgetting that the results are names rather than full paths.
  • Recursing manually when os.walk() or rglob() would already do the job.
  • Assuming hidden files are excluded by default when they usually are not.
  • Mixing string paths and Path objects inconsistently in the same function.
  • Walking huge directory trees without any filtering and then wondering why the script is slow.

Summary

  • 'pathlib.Path.iterdir() is a clean choice for listing one directory.'
  • 'os.walk() is a strong built-in tool for recursive directory traversal.'
  • 'Path.rglob() is convenient when you want recursive searches with patterns.'
  • Be careful about full paths versus bare entry names.
  • Pick the API based on whether you need flat listing, recursion, or pattern matching.

Related reading
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
Track 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.

Browse interview questions

All Rights Reserved.