fnmatch — Unix filename pattern matching

소스 코드: Lib/fnmatch.py


이 모듈은 유닉스 셸 스타일의 와일드카드를 지원하며, 이는 정규식(re 모듈에서 설명합니다)과는 다릅니다. 셸 스타일 와일드카드에 사용되는 특수 문자는 다음과 같습니다:

패턴

의미

*

모든 것과 일치합니다

?

모든 단일 문자와 일치합니다

[seq]

seq의 모든 문자와 일치합니다.

[!seq]

seq에 없는 모든 문자와 일치합니다

리터럴 일치의 경우, 대괄호 안에 메타 문자를 넣습니다. 예를 들어, '[?]''?' 문자와 일치합니다.

파일명 분리 기호(유닉스에서 '/')는 이 모듈에서 특수하지 않습니다. 경로명 확장은 모듈 glob을 참조하십시오 (glob은 경로명 세그먼트와 일치시키기 위해 filter()를 사용합니다). 마찬가지로, 마침표로 시작하는 파일명은 이 모듈에서 특수하지 않으며, *? 패턴과 일치합니다.

Also note that functools.lru_cache() with the maxsize of 32768 is used to cache the compiled regex patterns in the following functions: fnmatch(), fnmatchcase(), filter().

fnmatch.fnmatch(name, pat)

파일명 문자열 name이 패턴 문자열 pat와 일치하는지를 검사하여, TrueFalse를 반환합니다. 두 매개 변수는 모두 os.path.normcase()를 사용하여 대소 문자를 정규화합니다. fnmatchcase()는 운영 체제의 표준인지에 관계없이, 대소문자를 구분하는 비교를 수행하는 데 사용할 수 있습니다.

이 예제는 현재 디렉터리의 확장자 .txt 인 모든 파일 이름을 인쇄합니다:

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
fnmatch.fnmatchcase(name, pat)

파일명 문자열 name이 패턴 문자열 pat와 일치하는지를 검사하여, TrueFalse를 반환합니다; 비교는 대소 문자를 구분하며, os.path.normcase()를 적용하지 않습니다.

fnmatch.filter(names, pat)

Construct a list from those elements of the iterable names that match pattern pat. It is the same as [n for n in names if fnmatch(n, pat)], but implemented more efficiently.

fnmatch.translate(pat)

Return the shell-style pattern pat converted to a regular expression for using 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'>

더 보기

모듈 glob

유닉스 셸 스타일 경로 확장.