On this page
  1. fnmatch
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Filtering Paths Against Multiple Ignore Patterns
  7. 2. Compiling a Wildcard to a Regex (fnmatch.translate)
  8. Gotchas & Boundaries
  9. Common Functions

fnmatch

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


Import

import fnmatch

Overview

Unix shell-style wildcard matching (*, ?, [seq], [!seq]) against plain filename strings (fnmatch, fnmatchcase, filter, translate). Reach for fnmatch when filtering in-memory lists of names (e.g., ignore rules or archive member lists); use pathlib (Path.glob) or glob to match files directly on disk.

Quick Start

import fnmatch

files = ["app.py", "test_app.py", "README.md", "notes.txt"]
assert fnmatch.filter(files, "*.py") == ["app.py", "test_app.py"]
assert fnmatch.fnmatchcase("README.md", "*.md")
assert not fnmatch.fnmatchcase("README.MD", "*.md")

Implementation Walkthrough

1. Filtering Paths Against Multiple Ignore Patterns

import fnmatch

def is_ignored(name: str, patterns: tuple[str, ...]) -> bool:
    return any(fnmatch.fnmatchcase(name, pat) for pat in patterns)

ignore = ("*.pyc", "*.tmp", ".DS_Store")
kept = [n for n in ("main.py", "main.pyc", ".DS_Store", "data.json") if not is_ignored(n, ignore)]
assert kept == ["main.py", "data.json"]

2. Compiling a Wildcard to a Regex (fnmatch.translate)

import fnmatch, re

pat = re.compile(fnmatch.translate("log-2026-*.txt"))
assert pat.match("log-2026-12.txt") is not None

Gotchas & Boundaries

Common Functions

Linked from

Related notes