• fnmatch —- Unix filename pattern matching

    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, returningTrue or False. Both parameters are case-normalizedusing os.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:

    1. import fnmatch
    2. import os
    3.  
    4. for file in os.listdir('.'):
    5. if fnmatch.fnmatch(file, '*.txt'):
    6. 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().

    示例:

    1. >>> import fnmatch, re
    2. >>>
    3. >>> regex = fnmatch.translate('*.txt')
    4. >>> regex
    5. '(?s:.*\\.txt)\\Z'
    6. >>> reobj = re.compile(regex)
    7. >>> reobj.match('foobar.txt')
    8. <re.Match object; span=(0, 10), match='foobar.txt'>

    参见

    • Module glob
    • Unix shell-style path expansion.