fnmatch
--- Unix 檔案名稱模式比對¶
原始碼: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 | 含義 |
---|---|
| 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.
Unless stated otherwise, "filename string" and "pattern string" either refer tostr
orISO-8859-1
encodedbytes
objects. Note that thefunctions documented below do not allow to mix abytes
pattern withastr
filename, and vice-versa.
Finally, note thatfunctools.lru_cache()
with amaxsize of 32768is used to cache the (typed) compiled regex patterns in the followingfunctions:fnmatch()
,fnmatchcase()
,filter()
.
- fnmatch.fnmatch(name,pat)¶
Test whether the filename stringname matches the pattern stringpat,returning
True
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(name,pat)¶
Test whether the filename stringname matches the pattern stringpat,returning
True
orFalse
;the comparison is case-sensitive and does not applyos.path.normcase()
.
- fnmatch.filter(names,pat)¶
Construct a list from those elements of theiterable of filenamestringsnames that match the pattern stringpat.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()
. The pattern is expected to be astr
.範例:
>>>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'>
也參考
glob
模組Unix shell-style path expansion.