python
18 lines · 6 steps
Filtering files with pathlib.glob
A generator streams matching source files while a helper collects config files across several patterns.
Explained by
highlit
1from pathlib import Path
2from typing import Iterator
3
4
5def find_source_files(root: Path, pattern: str = "**/*.py") -> Iterator[Path]:
6 ignored = {".git", "__pycache__", ".venv", "node_modules"}
7 for path in sorted(root.glob(pattern)):
8 if any(part in ignored for part in path.parts):
9 continue
10 if path.is_file():
11 yield path
12
13
14def collect_configs(root: Path) -> list[Path]:
15 matches: list[Path] = []
16 for pattern in ("*.ini", "*.toml", "*.yaml", "*.yml", ".env*"):
17 matches.extend(root.glob(pattern))
18 return sorted(set(matches))
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Yielding paths lets callers process files lazily instead of building a full list in memory.
- 2Checking path.parts against an ignore set skips whole directory trees cheaply.
- 3Running multiple globs and deduplicating with a set gives clean, sorted results.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/filtering-files-with-pathlib-glob-explained-python-9104/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.