Searching Files by Content/Extension
Find files by extension
find_by_extension.py
from pathlib import Path
root = Path(".")
for p in root.rglob("*.md"):
print(p)find_by_extension.py
from pathlib import Path
root = Path(".")
for p in root.rglob("*.md"):
print(p)Search file contents
This example searches for a word in .py.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")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")Tips
- skip binary files
- limit walking large folders
- consider ripgrep for huge repos
๐งช Try It Yourself
Exercise 1 โ List Files with os.listdir
Exercise 2 โ Join Paths with os.path.join
Exercise 3 โ Write and Read a File
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
