PythonMastery
Python programs · Files · beginner

List all files in a folder in Python

List the files in a folder with pathlib.Path.iterdir(), filter them by extension with glob(), and search subfolders with rglob().

Path(".").iterdir() gives every file and folder inside a folder. Keep the files with is_file(), and sort the names, because the operating system does not return them in any fixed order.

The program

python
from pathlib import Path

# make a small folder to list
Path("project").mkdir()
Path("project/main.py").write_text("print('hi')\n")
Path("project/notes.txt").write_text("todo\n")
Path("project/data.csv").write_text("a,b\n")
Path("project/images").mkdir()

folder = Path("project")
files = sorted(p.name for p in folder.iterdir() if p.is_file())

for name in files:
    print(name)
print(f"{len(files)} files")
output
data.csv
main.py
notes.txt
3 files

How it works

Only some files

glob() matches names with a pattern: * means "any characters". rglob() does the same in every subfolder too:

python
from pathlib import Path

Path("project/src").mkdir(parents=True)
Path("project/setup.py").write_text("")
Path("project/README.md").write_text("")
Path("project/src/app.py").write_text("")
Path("project/src/utils.py").write_text("")

folder = Path("project")
print("Top level:", sorted(p.name for p in folder.glob("*.py")))
print("All:", sorted(p.as_posix() for p in folder.rglob("*.py")))
output
Top level: ['setup.py']
All: ['project/setup.py', 'project/src/app.py', 'project/src/utils.py']

as_posix() writes the path with /, so the output is the same on Windows, where paths normally use \.

Learn the idea: File I/O, Pathlib, and Large Files, Task Automation: Scripting the Boring Parts

A longer explanation: How do I list all files in a folder in Python?