coding
list
directory
files

How do I list all files of a directory?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Listing files in a directory is simple until you need to decide what "list files" actually means. Do you want only direct children, recursive traversal, file names only, full paths, hidden files, or a filtered pattern such as only .txt files.

The Cleanest Modern Option: pathlib

In current Python code, pathlib is usually the clearest API. It gives you path objects instead of raw strings and reads well for both one-level and recursive traversal.

To list only files in one directory level:

python
1from pathlib import Path
2
3folder = Path(".")
4for path in folder.iterdir():
5    if path.is_file():
6        print(path.name)

iterdir() returns both files and subdirectories, so the is_file() check is what keeps the result focused on files.

If you want full paths instead of names, print path instead of path.name.

Recursive Listing

If the directory tree should be searched recursively, use rglob.

python
1from pathlib import Path
2
3folder = Path(".")
4for path in folder.rglob("*"):
5    if path.is_file():
6        print(path)

This walks through subdirectories automatically. It is the simplest answer when you want every file anywhere under a root folder.

You can also filter by pattern:

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

That avoids manually checking file extensions afterward.

os.scandir for Efficient Flat Listing

If you want a direct-child listing and care about efficiency, os.scandir is a strong option.

python
1import os
2
3with os.scandir(".") as entries:
4    for entry in entries:
5        if entry.is_file():
6            print(entry.name)

This is faster than calling os.listdir() and then os.path.isfile() for each entry because directory metadata is exposed more directly.

os.walk for Recursive Traversal

os.walk is older than pathlib, but it is still useful and widely seen in existing codebases.

python
1import os
2
3for root, dirs, files in os.walk("."):
4    for filename in files:
5        print(os.path.join(root, filename))

This gives you explicit access to each directory, its subdirectories, and its files. That makes it easy to skip folders, apply custom traversal rules, or stop early once you find what you need.

Which Approach Should You Use

A practical rule is:

  • use pathlib for most modern scripts
  • use os.scandir for efficient one-level listings
  • use os.walk when you need detailed recursive control

os.listdir() still works, but it is rarely the most expressive or efficient answer today.

Be clear about what should count as a file in your program.

Hidden files are still files. On Unix-like systems, they simply start with a dot. If you need to exclude them, add a name check such as not path.name.startswith('.').

Symlinks also deserve attention. Depending on the API and options you use, a symlink may be treated as a file-like entry even when it points elsewhere. If your script walks large directory trees, decide deliberately whether following symlinks is safe.

Common Pitfalls

Using os.listdir() and assuming it returns only files is a common mistake. It returns directory entries, which include subdirectories.

Printing only path.name when you later need the full path also causes avoidable bugs, especially in recursive scripts.

Recursive listing can become slow on large trees if you do not filter early. If you only want one extension, apply the pattern during traversal instead of after collecting everything.

Finally, be careful with symlink loops or network-mounted directories if you are traversing a very large tree.

Summary

  • use pathlib.Path.iterdir() for a clean one-level listing of files
  • use Path.rglob() when you need recursive traversal or pattern matching
  • use os.scandir() for efficient flat directory scans
  • use os.walk() when you need full control over recursive walking
  • decide explicitly whether hidden files, symlinks, and full paths should be included in your result

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.