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

[seq]

matches any character inseq

[!seq]

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.

fnmatch.fnmatch(filename,pattern)

Test whether thefilename string matches thepattern string, returningTrue orFalse. 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(filename,pattern)

Test whetherfilename matchespattern, returningTrue orFalse; the comparison is case-sensitive and does not applyos.path.normcase().

fnmatch.filter(names,pattern)

Construct a list from those elements of the iterablenames that matchpattern. It is the same as[nforninnamesiffnmatch(n,pattern)], but implemented more efficiently.

fnmatch.translate(pattern)

Return the shell-stylepattern converted to a regular expression forusing withre.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

Moduleglob

Unix shell-style path expansion.