fnmatch — Unix filename pattern matching¶
Source code:Lib/fnmatch.py
This module provides support for Unix shell-style wildcards, which arenot thesame as regular expressions (which are documented in there module). Thespecial characters used in shell-style wildcards are:
Pattern | Meaning |
|---|---|
| matches everything |
| matches any single character |
| matches any character inseq |
| matches any character not inseq |
For a literal match, wrap the meta-characters in brackets.For example,'[?]' matches the character'?'.
Note that the filename separator ('/' on Unix) isnot special to thismodule. See moduleglob for pathname expansion (glob usesfilter() to match pathname segments). Similarly, filenames starting witha period are not special for this module, and are matched by the* and?patterns.
Also note thatfunctools.lru_cache() with themaxsize of 32768 is used tocache the compiled regex patterns in the following functions:fnmatch(),fnmatchcase(),filter().
- fnmatch.fnmatch(name,pat)¶
Test whether the filename stringname matches the pattern stringpat,returning
TrueorFalse. Both parameters are case-normalizedusingos.path.normcase().fnmatchcase()can be used to perform acase-sensitive comparison, regardless of whether that’s standard for theoperating system.This example will print all file names in the current directory with theextension
.txt:importfnmatchimportosforfileinos.listdir('.'):iffnmatch.fnmatch(file,'*.txt'):print(file)
- fnmatch.fnmatchcase(name,pat)¶
Test whether the filename stringname matches the pattern stringpat,returning
TrueorFalse;the comparison is case-sensitive and does not applyos.path.normcase().
- fnmatch.filter(names,pat)¶
Construct a list from those elements of theiterablenamesthat match patternpat.It is the same as
[nforninnamesiffnmatch(n,pat)],but implemented more efficiently.
- fnmatch.translate(pat)¶
Return the shell-style patternpat converted to a regular expression forusing with
re.match().Example:
>>>importfnmatch,re>>>>>>regex=fnmatch.translate('*.txt')>>>regex'(?s:.*\\.txt)\\Z'>>>reobj=re.compile(regex)>>>reobj.match('foobar.txt')<re.Match object; span=(0, 10), match='foobar.txt'>
See also
- Module
glob Unix shell-style path expansion.