SoFunction
Updated on 2025-04-29

Fnmatch module in Python implements file name matching

fnmatchModules are used for file name matching and support Unix shell-style wildcard characters (similar toglob), but does not match the path, only match the file name.

andglobThe difference is:

  • globIt is to search for matching files in the file system.
  • fnmatchOnly used to match string patterns, usually combined with()use.

1. ()

Match the file name whether it complies with a certain wildcard mode (case insensitive).

import fnmatch

# directly match file namesprint(("", "*.txt"))  # True
print(("", "*.txt"))  # False

2. ()

Strictly case sensitive matching.

import fnmatch

print(("", "*.txt"))  # False (different case)print(("", "*.TXT"))  # True

3. ()

Filter the list to return a list of file names that match the pattern.

import fnmatch

files = ["", "", "", ""]

# Filter out all .txt filestxt_files = (files, "*.txt")
print(txt_files)  # ['']

4. ()

Converts wildcard pattern to regular expression (regex).

import fnmatch

pattern = ("*.txt")
print(pattern)

Output:

(?s:.*\.txt)\Z

Can be used for()Make more complex matches.

5. Filter files in combination with ()

import os
import fnmatch

# Get all .txt files in the current directoryfiles = (".")
txt_files = (files, "*.txt")

print(txt_files)

6. fnmatch vs glob

Function fnmatch glob
Main uses String matching File search
Whether to look for files ❌ Match only names ✅ Scan the directory to get matching files
Common methods fnmatch(), filter() (), rglob()

7. Summary

  • (): Match string (file name).
  • (): Case-sensitive matching.
  • (): Filter files that match the pattern from the list.
  • (): Convert wildcards to regular expressions.

Suitable for string matching, such as file filtering, log analysis, path matching, etc. If you need to find files on disk, it is recommended to useglobor()Combined()

This is the article about the fnmatch module in Python that implements file name matching. For more related Python fnmatch module content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!