Think of .glob() as a search filter tool 🎯 that helps you find files and folders matching a pattern inside a directory.
from pathlib import Path
folder = Path("documents")
for file in folder.glob("*.txt"):
print(file)
👉 Finds all files ending with .txt in the documents folder.
"*.txt" → 📄 All text files
"*.pdf" → 📑 All PDFs
"*.jpg" or "*.png" → 🖼️ All images of given type
"*.*" → 🌍 Everything with an extension
"file_*.csv" → 🔢 Files starting with file_ and ending in .csv
.rglob()for file in folder.rglob("*.txt"):
print(file)
📂 .rglob() = Searches inside subfolders too (deep search).
# All Python files in current directory
for pyfile in Path(".").glob("*.py"):
print("Python file:", pyfile)
# All JPG files in images subfolder
for img in Path("images").glob("*.jpg"):
print("Image:", img)
.glob("pattern") → 🔍 Search in current folder
.rglob("pattern") → 🌎 Search in all subfolders too
Patterns (*, ?, [abc]) → 🎭 Act like wildcards
👉 In short:
.glob() = File finder 🎯,
.rglob() = Deep explorer 🗂️