PythonMastery

How do I list all files in a folder in Python?

Path('folder').glob('*.csv') lists what matches, iterdir() lists everything, rglob() goes into subfolders. Sort the result: the order isn't guaranteed.

Path.glob() lists the files that match a pattern. "*" matches everything.

python
from pathlib import Path

# Make a folder with a few files in it.
folder = Path("exports")
folder.mkdir(exist_ok=True)
for name in ["march.csv", "april.csv", "notes.txt"]:
    (folder / name).write_text("data\n", encoding="utf-8")

for path in sorted(folder.glob("*.csv")):
    print(path.name)
output
april.csv
march.csv

sorted() matters. The operating system returns files in whatever order suits it, and that order differs between Windows, macOS and Linux.

Everything in the folder, files only

iterdir() returns everything, subfolders included. Filter with is_file():

python
from pathlib import Path

folder = Path("inbox")
(folder / "old").mkdir(parents=True, exist_ok=True)     # a subfolder, to be left out
for name in ["march.csv", "notes.txt"]:
    (folder / name).write_text("data\n", encoding="utf-8")

files = sorted(p.name for p in folder.iterdir() if p.is_file())
print(files)
output
['march.csv', 'notes.txt']

Into subfolders too

rglob() is glob() that goes all the way down:

python
from pathlib import Path

for name in ["2025/jan.csv", "2025/feb.csv", "2026/jan.csv", "readme.txt"]:
    path = Path("archive") / name
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("data\n", encoding="utf-8")

for path in sorted(Path("archive").rglob("*.csv")):
    print(path.as_posix())
output
archive/2025/feb.csv
archive/2025/jan.csv
archive/2026/jan.csv

as_posix() prints forward slashes on every system; on Windows a plain print(path) shows backslashes.

You will see os.listdir() in older answers. It still works, but it returns bare names that you then have to join back onto the folder yourself. pathlib returns paths you can open directly.

Go deeper: File I/O, Pathlib, and Large Files, Task Automation: Scripting the Boring Parts, Project: File Organizer (Tidy a Messy Folder)

More short answers

all questions