fnmatch —- Unix filename pattern matching
Source code:Lib/fnmatch.py
This module provides support for Unix shell-style wildcards, which are not thesame as regular expressions (which are documented in the re
module). Thespecial characters used in shell-style wildcards are:
模式 | 含义 |
---|---|
* | 匹配所有 |
? | 匹配任何单个字符 |
[seq] | 匹配 seq 中的任何字符 |
[!seq] | 匹配任何不在 seq 中的字符 |
For a literal match, wrap the meta-characters in brackets.For example, '[?]'
matches the character '?'
.
Note that the filename separator ('/'
on Unix) is not special to thismodule. See module glob
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 the filename string matches the pattern string, 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
:
- import fnmatch
- import os
- for file in os.listdir('.'):
- if fnmatch.fnmatch(file, '*.txt'):
- print(file)
fnmatch.
fnmatchcase
(filename, pattern)- Test whether filename matches pattern, returning
True
orFalse
; the comparison is case-sensitive and does not applyos.path.normcase()
.
fnmatch.
filter
(names, pattern)- Return the subset of the list of names that match pattern. It is the same as
[n for n in names if fnmatch(n, pattern)]
, but implemented more efficiently.
fnmatch.
translate
(pattern)- Return the shell-style pattern converted to a regular expression forusing with
re.match()
.
示例:
- >>> import fnmatch, 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'>
参见
- Module
glob
- Unix shell-style path expansion.