Searching Files by Content/Extension
flowchart TD
A["os.walk / rglob"] --> B["prune directories you never want"]
B --> C{"does the name match?"}
C -->|no| D["skip -- no file was opened"]
C -->|yes| E{"searching content too?"}
E -->|no| F["report it"]
E -->|yes| G["open it"]
G --> H{"is it text?"}
H -->|no| I["UnicodeDecodeError -- catch it, or open in binary"]
H -->|yes| J["scan line by line, not read()"]
J --> K["report the path and line number"]
Find files by extension
Section titled “Find files by extension”from pathlib import Path
root = Path(".")
for p in root.rglob("*.md"):
print(p)Search file contents
Section titled “Search file contents”This example searches for a word in .py files.
from pathlib import Path
def search_word(root: Path, word: str):
for p in root.rglob("*.py"):
try:
text = p.read_text(encoding="utf-8")
except UnicodeDecodeError:
continue
if word in text:
print("found in", p)
search_word(Path("."), "asyncio")- skip binary files
- limit walking large folders
- consider ripgrep for huge repos
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading