The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Use Python’s pathlib module for a simple directory listing. Path.iterdir() returns paths for the directory’s immediate children, including both files and subdirectories:
from pathlib import Path
folder = Path(".")
entries = list(folder.iterdir())
print(entries)
To list files only, filter those entries with is_file(). The examples below show how to list names, match extensions, search recursively, and traverse a directory tree.
List files in one directory
Path.iterdir() lists the immediate contents of a directory; it does not search inside subdirectories. Its results are Path objects and can include files, folders, and other entries. The order is arbitrary, so sort the paths if a consistent display order matters. See the Python 3.14.7 pathlib documentation.
from pathlib import Path
folder = Path(".")
for entry in folder.iterdir():
print(entry)
Replace "." with a directory path, such as "/var/log" or r"C:\Users\Sam\Documents". A path that cannot be accessed, or that is not a directory, raises an OSError.
#1 Best Overall
Show files only
Use is_file() to exclude directories:
files = [entry for entry in folder.iterdir() if entry.is_file()]
for file in files:
print(file)
Show subdirectories only
Use is_dir() when you want only immediate subdirectories:
directories = [entry for entry in folder.iterdir() if entry.is_dir()]
List entry names instead of paths
os.listdir() returns the names of entries in a directory as strings. It excludes the special . and .. entries, and its results have arbitrary order. Use it when names are all you need; unlike Path.iterdir(), it does not return paths you can directly use for path operations.
Rank #2
import os
names = os.listdir(".")
print(names)
To build a full path from each name, join it to the directory:
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →from pathlib import Path
folder = Path(".")
for name in os.listdir(folder):
print(folder / name)
The Python 3.14.7 os documentation also describes os.scandir(), which yields DirEntry objects. Consider it when you need file types or attributes for many entries: the Python documentation says it can significantly improve performance for that kind of work, but the benefit depends on the operating system and workload.
Filter by file name or extension
Use Path.glob() to select matching entries in one directory level. For example, this returns paths matching the *.py pattern:
python_files = list(Path(".").glob("*.py"))
for file in sorted(python_files):
print(file)
Sorting is optional, but useful when output needs a predictable order. By default, pathlib globbing includes dot-prefixed names in normal pattern matching. Its case sensitivity follows platform conventions unless you specify the case_sensitive option, available from Python 3.12.
List files recursively
For matching files throughout a directory tree, use Path.rglob():
from pathlib import Path
python_files = sorted(Path(".").rglob("*.py"))
for file in python_files:
print(file)
rglob("*.py") is equivalent to matching with **/*.py. Recursive searches can take a long time on large directory trees. Results are not guaranteed to arrive in a particular order, so sort them when stable output is required.
Best Value
By default, glob() and rglob() do not recurse through symlinked directories. On current Python versions, the recurse_symlinks option can change that behavior. In Python 3.13 and later, these methods suppress any OSError raised during scanning; if errors must be reported instead of silently skipped, choose an API with error handling suited to that requirement.
Walk a directory tree one level at a time
Use Path.walk() when you need to process each directory along with its subdirectory and file names. It was added in Python 3.12:
from pathlib import Path
for directory, dirnames, filenames in Path(".").walk():
for filename in filenames:
print(directory / filename)
For each directory, dirnames contains subdirectory names and filenames contains non-directory names. By default, Path.walk() does not follow symlinks to directories. Scanning errors are ignored unless you supply an on_error handler. Following directory symlinks can cause infinite recursion if a link points to a parent.
For versions of Python earlier than 3.12, use os.walk() for the same kind of level-by-level traversal:
Quick Recap
import os
for directory, dirnames, filenames in os.walk("."):
for filename in filenames:
print(os.path.join(directory, filename))
Choose the right directory-listing method
| Task | Method | What it provides |
|---|---|---|
| List immediate children | Path.iterdir() |
Path objects; includes files and directories. |
| Get immediate entry names | os.listdir() |
Names as strings, or bytes when given a bytes path. |
| Match names in one directory | Path.glob() |
Matching paths; use a recursive pattern when needed. |
| Find matches throughout a tree | Path.rglob() |
Matching paths recursively. |
| Process each directory and its contents | Path.walk() (Python 3.12+) or os.walk() |
Directory paths, subdirectory names, and file names, one level at a time. |
| Check types or attributes while scanning | os.scandir() |
DirEntry objects with entry information; may be faster than listdir() when that information is needed. |
Ordering, hidden names, and changing directories
- Order:
iterdir(),listdir(), and globbing do not guarantee a useful order. Applysorted()when results need to be deterministic. - Hidden names:
pathlibglob patterns include dot-prefixed names by default. Theglobmodule behaves differently: by default, its pattern must begin with a dot to match a dot-prefixed name. See the Python 3.16.0a0 glob documentation. - Directory changes: If entries are added or removed while a directory is being iterated or scanned, whether those changes appear in the results is unspecified.
- Scanning errors:
iterdir()can raiseOSErrorfor an inaccessible or invalid directory. In Python 3.13 and later,Path.glob()andPath.rglob()suppress scanningOSErrorexceptions.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

