Finding Files with glob & fnmatch

Published by Brayan K

The glob module finds real files on disk that match a wildcard pattern, while fnmatch tests whether a filename string matches such a pattern — together they make file searching simple and readable.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Matching a name does not search the filesystem

fnmatch tests whether a supplied string fits a wildcard pattern. glob searches a directory tree for matching pathnames. Keep those jobs separate: testing the name of a file does not prove that the file exists, and finding a pathname does not prove it is a regular file. Modern File Paths with pathlib owns Path objects and path construction; here the focus is matching policy.

from fnmatch import fnmatchcase

print(fnmatchcase("report.csv", "*.csv"))
print(fnmatchcase("report1.csv", "report?.csv"))
print(fnmatchcase("report12.csv", "report?.csv"))
print(fnmatchcase("report7.csv", "report[0-9].csv"))
print(fnmatchcase("reportx.csv", "report[!0-9].csv"))

# ✅ Expected output:
# True
# True
# False
# True
# True

A star accepts any number of characters, including none. A question mark accepts exactly one. Brackets select one character from a set or range, and an initial exclamation mark negates the set. These are shell-style wildcards, not regular expressions: a dot has no special regex meaning here. Regular Expressions (re) owns regular-expression syntax.

from fnmatch import fnmatchcase

print(fnmatchcase("nested/report.csv", "*.csv"))
print(fnmatchcase(".private.csv", "*.csv"))
print(fnmatchcase("Report.CSV", "*.csv"))
print(fnmatchcase("Report.CSV".casefold(), "*.csv"))

# ✅ Expected output:
# True
# True
# False
# True

fnmatchcase applies the pattern to the whole supplied string, with no special treatment for path separators or a leading dot. fnmatch instead normalizes case using the operating system’s normcase rules, so identical text can match differently on different platforms. Choose fnmatchcase for explicit case-sensitive rules; normalize both the input and pattern yourself when your application specifies case-insensitive matching.

Search an owned directory and sort before reporting

from glob import glob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    for name, text in [("b.txt", "beta"), ("a.txt", "alpha"),
                       ("notes.csv", "ignored")]:
        (root / name).write_text(text, encoding="utf-8")
    matches = sorted(glob("*.txt", root_dir=root))
    print(len(matches))
    print([(root / name).read_text(encoding="utf-8")
           for name in matches])

# ✅ Expected output:
# 2
# ['alpha', 'beta']

root_dir makes the search location explicit without changing the process working directory. A relative pattern returns names relative to that root. Join them back to the root when opening them. Glob results have no guaranteed order; sorting is what makes this report stable. Sorting is a presentation decision, not a property the filesystem promises.

from glob import glob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    (root / "one.txt").write_text("one", encoding="utf-8")
    print(glob("*.json", root_dir=root) == [])
    (root / "folder.txt").mkdir()
    selected = glob("*.txt", root_dir=root)
    print(len(selected))
    print(sum((root / name).is_file() for name in selected))

# ✅ Expected output:
# True
# 2
# 1

glob does not raise simply because nothing matches. A pathname ending in .txt can also be a directory; apply is_file when the operation needs regular files. That check is still an observation: another process could remove or replace the file before you open it. Handle the actual open failure where it occurs rather than treating a search result as a reservation.

Recursion and hidden entries are separate choices

from glob import glob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    (root / "child").mkdir()
    (root / "top.txt").write_text("top", encoding="utf-8")
    (root / "child" / "deep.txt").write_text("deep", encoding="utf-8")
    direct = glob("*.txt", root_dir=root)
    recursive = glob("**/*.txt", root_dir=root, recursive=True)
    print(len(direct))
    print(len(recursive))
    print(sorted((root / name).read_text(encoding="utf-8")
                 for name in recursive))

# ✅ Expected output:
# 1
# 2
# ['deep', 'top']

The special recursive meaning of ** needs recursive=True. It can include the root level as well as descendants; do not assume that **/*.txt means only nested files. Multiple recursive stars can produce duplicate pathnames. If the application requires each path once, deduplicate before processing and then impose the required order.

from glob import glob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    (root / "visible.txt").write_text("public", encoding="utf-8")
    (root / ".hidden.txt").write_text("private", encoding="utf-8")
    print(len(glob("*.txt", root_dir=root)))
    print(len(glob(".*.txt", root_dir=root)))
    print(len(glob("*.txt", root_dir=root, include_hidden=True)))

# ✅ Expected output:
# 1
# 1
# 2

For glob, leading-dot names need explicit consideration. include_hidden is available throughout the supported Python 3.11–3.14 range, and recursive traversal of hidden directories also depends on that option. These are glob rules, not universal rules for every matching API: fnmatchcase and Path.glob handle leading dots differently. Test the function your program actually uses.

Escape literal wildcard characters and keep string types consistent

from glob import escape, glob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    name = "report[1].txt"
    (root / name).write_text("literal brackets", encoding="utf-8")
    print(len(glob(name, root_dir=root)))
    matches = glob(escape(name), root_dir=root)
    print(len(matches))
    print((root / matches[0]).read_text(encoding="utf-8"))

# ✅ Expected output:
# 0
# 1
# literal brackets

Without escaping, [1] means one character selected from the bracket expression, so it does not match literal brackets in the filename. glob.escape protects wildcard characters in literal input. It is not an access-control mechanism and does not turn an arbitrary path into a safe child of a directory. Keep file-operation boundaries separate from pattern syntax.

from fnmatch import fnmatchcase

fnmatchcase("report.txt", b"*.txt")

# ✅ Expected error:
# TypeError: cannot use a bytes pattern on a string-like object

Use strings consistently for ordinary filenames and patterns. If an API requires bytes paths, keep both sides in that representation and understand the platform constraints. Encoding rules belong to Strings, Bytes & Unicode Encodings.

Iterate matches without first keeping the whole result list

from glob import iglob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    for index in range(3):
        (root / (str(index) + ".txt")).write_text("x", encoding="utf-8")
    matches = iglob("*.txt", root_dir=root)
    print(sum(1 for _ in matches))
    print(list(matches))

# ✅ Expected output:
# 3
# []

iglob yields results as an iterator rather than returning the complete list. After consumption it is exhausted. It does not promise sorted order or a frozen snapshot, and internal traversal can still use memory. If you sort the iterator you deliberately materialize its results; that tradeoff can be worthwhile for reproducible reporting.

Complete an explicit selection policy

Find only regular .txt files in an owned directory, then report their contents in filename order. The fixture includes a directory with the same suffix so an extension check alone is insufficient.

from glob import glob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    (root / "b.txt").write_text("B", encoding="utf-8")
    (root / "a.txt").write_text("A", encoding="utf-8")
    (root / "skip.txt").mkdir()
    names = ___(glob("*.txt", root_dir=root))
    files = [root / name for name in names if (root / name).___()]
    print([file.read_text(encoding="utf-8") for file in files])

# 👉 replace ___ with sorted
# 👉 replace ___ with is_file

# ✅ Expected output:
# ['A', 'B']

Produce a report from selected visible records

Create root and nested fixture files containing one numeric score each. Select visible .txt files recursively, exclude directories, sum their integer contents and print the file count and total. Include a hidden .txt fixture and a .csv fixture that must not participate. Keep filenames and temporary directory names out of the report.

from glob import glob
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    root = Path(directory)
    (root / "nested").mkdir()
    fixtures = [("one.txt", "10"), ("nested/two.txt", "20"),
                (".hidden.txt", "500"), ("ignored.csv", "900")]
    for name, text in fixtures:
        (root / name).write_text(text, encoding="utf-8")
    (root / "directory.txt").mkdir()
    files = [root / name
             for name in sorted(glob("**/*.txt", root_dir=root, recursive=True))
             if (root / name).is_file()]
    print(len(files))
    print(sum(int(file.read_text(encoding="utf-8")) for file in files))

# ✅ Expected output:
# 2
# 30

Practice quiz

What does this program print? from fnmatch import fnmatchcase print(fnmatchcase("a/b.txt", "*.txt"))

  • True
  • False
  • None
  • FileNotFoundError

Answer: True. fnmatchcase treats the slash as an ordinary character; it does not traverse directories.

What does this program print? from fnmatch import fnmatchcase print(fnmatchcase("item12", "item?"))

  • True
  • False
  • None
  • 12

Answer: False. The question mark matches exactly one character, not two.

Which step makes glob result reporting deterministic?

  • Trust directory creation order
  • Use iglob instead
  • Sort the results using the required ordering
  • Add a trailing slash

Answer: Sort the results using the required ordering. Neither glob nor iglob guarantees ordering.

What does this program print? from fnmatch import fnmatchcase print(fnmatchcase(".secret", "*"))

  • False
  • None
  • PermissionError
  • True

Answer: True. Leading dots are not special to fnmatchcase.

What does this program print? from fnmatch import fnmatchcase print(fnmatchcase("Report.CSV", "*.csv"))

  • False
  • True
  • None
  • An operating-system-dependent result

Answer: False. fnmatchcase performs case-sensitive matching without OS case normalization.

A search finds a path ending in .txt. What has that established?

  • It is definitely a readable text file
  • Only that the pathname matched the pattern
  • It cannot be a directory
  • It will still exist when opened

Answer: Only that the pathname matched the pattern. Matching does not validate file type, encoding, permissions or future existence.

What does this program print? from fnmatch import fnmatchcase print(fnmatchcase("log7", "log[!0-9]"))

  • True
  • None
  • False
  • 7

Answer: False. The negated character class rejects the digit.

What does glob.escape provide for user-supplied literal text?

  • Permission to read it
  • A guarantee that it remains inside a trusted directory
  • Recursive search automatically
  • Literal treatment of wildcard characters

Answer: Literal treatment of wildcard characters. Escaping pattern metacharacters is distinct from validating filesystem access boundaries.

Continue this course

Related lessons