Automate everyday tasks with Python · Lesson 3 of 14
Listing and finding files
List what is in a folder with iterdir(), find files by pattern with glob() and rglob(), and count files by type, always in a fixed order.
Before a script can rename or move files, it has to find them. pathlib gives you three tools: iterdir() lists what is directly inside a folder, glob() finds names that match a pattern, and rglob() does the same search through all the folders below as well. The examples use a small inbox folder that is created before the code runs: three files at the top, an old folder with two more files and an old/2025 folder with one.
What is in a folder: iterdir()
iterdir() gives one path for each file and folder directly inside. The order it returns them in depends on the computer, so always sort the result. Sorting by name gives the same order everywhere.
from pathlib import Path
inbox = Path("inbox")
for p in sorted(inbox.iterdir(), key=lambda p: p.name):
if p.is_dir():
print(p.name + "/")
else:
print(p.name)notes.txt old/ photo1.jpg photo2.jpg report.pdf
Matching a pattern: glob()
A glob pattern is a name with wildcards: * means "any characters", ? means "exactly one character". *.jpg matches every name ending in .jpg, photo?.jpg matches photo1.jpg but not photo10.jpg.
from pathlib import Path
inbox = Path("inbox")
print(sorted(p.name for p in inbox.glob("*.jpg")))
print(sorted(p.name for p in inbox.glob("photo?.*")))
print(sorted(p.name for p in inbox.glob("*.png")))['photo1.jpg', 'photo2.jpg'] ['photo1.jpg', 'photo2.jpg'] []
Searching all sub-folders: rglob()
rglob("*.jpg") searches the folder and every folder inside it, at any depth. To show where each file was found, print its path relative to the starting folder.
from pathlib import Path
inbox = Path("inbox")
found = sorted(p.relative_to(inbox).as_posix() for p in inbox.rglob("*.txt"))
for name in found:
print(name)
print(len(found), "text files")notes.txt old/2025/summary.txt 2 text files
*.jpg does not match HOLIDAY.JPG, on Windows it does. To find files by type on every system, compare p.suffix.lower() instead of relying on the pattern, as in the next example.Counting files by type
rglob("*") returns everything, folders included, so keep only real files with is_file(). A dictionary then counts the extensions.
from pathlib import Path
inbox = Path("inbox")
counts = {}
for p in inbox.rglob("*"):
if p.is_file():
ext = p.suffix.lower()
counts[ext] = counts.get(ext, 0) + 1
for ext in sorted(counts):
print(f"{ext:6} {counts[ext]}").jpg 3 .pdf 1 .txt 2 .xlsx 1
You can also create sample files at the start of a script with touch(), which makes an empty file. This is handy for trying an idea quickly. Here we find every file whose name contains the word draft, in any case.
from pathlib import Path
work = Path("work")
work.mkdir(exist_ok=True)
for name in ["letter_draft.docx", "Draft-plan.txt", "final.pdf", "notes.txt"]:
(work / name).touch()
drafts = sorted(p.name for p in work.iterdir() if "draft" in p.name.lower())
print(drafts)['Draft-plan.txt', 'letter_draft.docx']
✎ Exercise
Find every .txt file anywhere inside the notes folder. Print each one as a path relative to notes (forward slashes), in sorted order, then print how many there are as <n> files.
Hint: Use rglob("*.txt"), then relative_to(notes).as_posix() for each path, and sort the strings.
from pathlib import Path
notes = Path("notes")
# your code here
Expected output:
home/recipes/soup.txt home/shopping.txt monday.txt work/meeting.txt 4 files
Show a solution
from pathlib import Path
notes = Path("notes")
found = sorted(p.relative_to(notes).as_posix() for p in notes.rglob("*.txt"))
for name in found:
print(name)
print(len(found), "files")home/recipes/soup.txt home/shopping.txt monday.txt work/meeting.txt 4 files
Check yourself
1. Why do we sort the result of iterdir()?
The order comes from the file system. sorted() gives the same order everywhere.
2. What is the difference between glob("*.txt") and rglob("*.txt")?
glob looks only in the folder itself (with this pattern); rglob also goes into every folder below it.
3. Which pattern matches photo7.jpg but not photo17.jpg?
? stands for exactly one character, * for any number.