Home / Python / Example programs / Files and data

Python program: List files by type

Find all files with a given extension in a folder, with their sizes.

The code

from pathlib import Path

folder = Path("demo")
folder.mkdir(exist_ok=True)
for name, text in [("a.csv", "x,y\n1,2\n"), ("b.txt", "hello"), ("c.csv", "z\n3\n")]:
    (folder / name).write_text(text, encoding="utf-8")

for p in sorted(folder.glob("*.csv")):
    print(p.name, p.stat().st_size, "bytes")
print(len(list(folder.iterdir())), "files in total")

Output

a.csv 8 bytes
c.csv 4 bytes
3 files in total

How it works

Path.glob("*.csv") matches file names with a wildcard; rglob searches sub-folders too. stat().st_size is the size in bytes.

Learn the ideas behind it in the free lesson Files.