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.

PythonCli Tooling

Code

pythonsnippet
21 lines
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

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.