Skip to content

Searching Files by Content/Extension

diagram searching by name is cheap; searching by content is not mermaid
Filtering on the filename only needs the directory listing the walk already gave you. Looking inside means opening every candidate, which is where the cost is -- so narrow by extension and size first, read in chunks rather than whole, and be ready for files that are not text at all.
find_by_extension.py
from pathlib import Path
 
root = Path(".")
for p in root.rglob("*.md"):
    print(p)

This example searches for a word in .py files.

search_content.py
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

Exercise 2 – Join Paths with os.path.join

Section titled “Exercise 2 – Join Paths with os.path.join”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading