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
import asyncio from dataclasses import dataclass import aiohttp
Bounded-concurrency HTTP fetching with asyncio
async
concurrency
semaphore
Intermediate
8 steps
python
import heapq from collections import Counter from typing import Iterable, Hashable
Finding the top-N items in a stream
heaps
counting
generators
Intermediate
5 steps
python
from flask import Blueprint, jsonify from sqlalchemy import text from sqlalchemy.exc import SQLAlchemyError
Building a health check endpoint in Flask
health-check
blueprint
error-handling
Intermediate
6 steps
python
import pandas as pd import numpy as np
Cleaning a customer DataFrame with pandas
data-cleaning
regex
normalization
Intermediate
9 steps
python
from datetime import date, timedelta from typing import Annotated from fastapi import APIRouter, Depends, Query
Validating date ranges with FastAPI dependencies
dependency-injection
validation
pydantic
Intermediate
6 steps
python
from collections.abc import MutableMapping class CaseInsensitiveDict(MutableMapping):
Building a case-insensitive dict in Python
data structures
abstract base classes
dunder methods
Intermediate
8 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.