Glob Expands Patterns To File Lists
glob matches single levels with *, crosses directories only when ** is paired with recursive=True; results arrive in directory order, so sort them.
Code
import glob
import os
import tempfile
# Build a small tree so the patterns have something real to match
with tempfile.TemporaryDirectory() as root:
for rel in ("a.log", "sub/b.log", "sub/deep/c.txt", "other/d.log"):
path = os.path.join(root, rel)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write("x")
def show(pattern, recursive=False):
matches = glob.glob(os.path.join(root, pattern), recursive=recursive)
return sorted(os.path.relpath(m, root) for m in matches)
# Single star never crosses a directory separator
print("single:", show("*.log"))
# ** only descends when recursive=True is set
print("recursive:", show("**/*.log", recursive=True))
print("txt:", show("**/*.txt", recursive=True))Output
Captured from a sandboxed run of this snippet in the build pipeline.
single: ['a.log']
recursive: ['a.log', 'other\\d.log', 'sub\\b.log']
txt: ['sub\\deep\\c.txt']What the demo matches
A temp tree is built first, with a.log at the root, b.log and c.txt nested two levels deep and d.log in a sibling, so every pattern has real targets. show() globs and returns sorted relative paths, keeping output stable.
.log matches only the top level because a single star never crosses a directory separator. **/.log with recursive=True descends and finds all three logs, while **/*.txt locates the lone nested c.txt.
Points worth noting
- ** is inert without recursive=True; it degrades to a single star.
- Directory order is unspecified; the demo sorts before printing.
Interactive Tools for This Topic
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Why sort the glob results?
- glob returns matches in filesystem order, which varies; sorting the relative paths makes the printed output deterministic for tests and logs.
Report a problem with this exampleOpens a pre-filled issue on GitHub.