Python fnmatch — ELI5
Imagine you have a big toy box with hundreds of toys, and you want to find all the ones that are cars. You could pick up every single toy and check — or you could just say “give me everything that looks like a car” and let someone else sort through the box.
That’s what fnmatch does, but for filenames.
You give it a pattern with wildcards — special characters that mean “anything goes here”:
*means “any number of characters” — so*.txtmatches every text file?means “exactly one character” — sophoto_?.jpgmatchesphoto_1.jpgbut notphoto_12.jpg
fnmatch checks whether a filename matches your pattern. It’s the same kind of matching you use when you type ls *.py in a terminal.
Why not just search the whole name?
Wildcard patterns are simpler than the alternative (regular expressions). You don’t need to learn special syntax — *.txt just means “anything ending in .txt,” and that’s immediately obvious.
One thing to remember
fnmatch is wildcard matching for filenames — quick, readable patterns like *.py and report_??.csv that feel natural and get the job done without complexity.
See Also
- Python Atexit How Python's atexit module lets your program clean up after itself right before it shuts down.
- Python Bisect Sorted Lists How Python's bisect module finds things in sorted lists the way you'd find a word in a dictionary — by jumping to the middle.
- Python Contextlib How Python's contextlib module makes the 'with' statement work for anything, not just files.
- Python Copy Module Why copying data in Python isn't as simple as it sounds, and how the copy module prevents sneaky bugs.
- Python Dataclass Field Metadata How Python dataclass fields can carry hidden notes — like sticky notes on a filing cabinet that tools read automatically.