On this page
  1. glob
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Lazy Recursive Search with iglob() & root_dir
  7. 2. Escaping Literal Brackets in Directory Names (glob.escape)
  8. Gotchas & Boundaries
  9. Common Functions

glob

Prev: gettext | Up: stdlib_module | Next: graphlib
Rel: pathlib, os, io, time, fileinput
Ref: docs.python.org — glob
Tags: #public #python3 #stdlib


Import

import glob

Overview

Unix-style filesystem wildcard expansion (glob, iglob, escape, translate) with root_dir and recursive=True (**) support. Prefer Path.glob() / Path.rglob() from pathlib when already working with Path objects; reach for glob.iglob() when you want lazy string paths or include_hidden=True.

Quick Start

import glob
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    (Path(tmp) / "a.py").write_text("", encoding="utf-8")
    (Path(tmp) / "b.md").write_text("", encoding="utf-8")
    matches = glob.glob("*.py", root_dir=tmp)
    assert matches == ["a.py"]

Implementation Walkthrough

1. Lazy Recursive Search with iglob() & root_dir

iglob() yields paths lazily without materializing the entire list in memory, and root_dir avoids calling os.chdir():

import glob

def iter_markdown(root: str) -> list[str]:
    return sorted(glob.iglob("**/*.md", root_dir=root, recursive=True))

2. Escaping Literal Brackets in Directory Names (glob.escape)

If a base path might contain [ or ] (common in project folders or Next.js routes), escape it before appending a wildcard:

import glob

safe_pattern = glob.escape("/tmp/data[2026]") + "/*.json"
assert safe_pattern == "/tmp/data[[]2026]/*.json"

Gotchas & Boundaries

Common Functions

Linked from

Related notes