Python Fnmatch Module
The fnmatch module provides support for Unix shell-style wildcards, which are not the same as regular expressions (which are documented in the re module). The special characters used in shell-style wildcards are:
*: Matches everything.?: Matches any single character.[seq]: Matches any character in seq.[!seq]: Matches any character not in seq.
Importing the Module
import fnmatch
Matching Filenames
fnmatch()
Test whether the filename string matches the pattern string, returning True or False. Note that the case-sensitivity of this function depends on the operating system.
import fnmatch
import os
pattern = '*.py'
print(fnmatch.fnmatch('script.py', pattern)) # True
print(fnmatch.fnmatch('script.txt', pattern)) # False
fnmatchcase()
Test whether the filename matches the pattern, but the comparison is case-sensitive regardless of the operating system.
import fnmatch
print(fnmatch.fnmatchcase('Script.py', '*.py')) # False
print(fnmatch.fnmatchcase('script.py', '*.py')) # True
Filtering Lists
filter()
Return the subset of the list of names that match the pattern. It is the same as [n for n in names if fnmatch(n, pattern)], but implemented more efficiently.
import fnmatch
import os
files = ['script.py', 'data.csv', 'image.png', 'test.py']
py_files = fnmatch.filter(files, '*.py')
print(py_files)
# Output: ['script.py', 'test.py']
Translating to Regex
translate()
Return the shell-style pattern converted to a regular expression for using with re.match().
import fnmatch
import re
regex = fnmatch.translate('*.txt')
print(regex)
# Output (may vary slightly): (?s:.*\.txt)\Z
re_obj = re.compile(regex)
print(bool(re_obj.match('foobar.txt'))) # True