fnmatch
— 유닉스 파일명 패턴 일치¶
소스 코드: Lib/fnmatch.py
이 모듈은 유닉스 셸 스타일의 와일드카드를 지원하며, 이는 정규식(re
모듈에서 설명합니다)과는 다릅니다. 셸 스타일 와일드카드에 사용되는 특수 문자는 다음과 같습니다:
패턴 |
의미 |
---|---|
|
모든 것과 일치합니다 |
|
모든 단일 문자와 일치합니다 |
|
seq의 모든 문자와 일치합니다. |
|
seq에 없는 모든 문자와 일치합니다 |
리터럴 일치의 경우, 대괄호 안에 메타 문자를 넣습니다. 예를 들어, '[?]'
는 '?'
문자와 일치합니다.
파일명 분리 기호(유닉스에서 '/'
)는 이 모듈에서 특수하지 않습니다. 경로명 확장은 모듈 glob
을 참조하십시오 (glob
은 경로명 세그먼트와 일치시키기 위해 filter()
를 사용합니다). 마찬가지로, 마침표로 시작하는 파일명은 이 모듈에서 특수하지 않으며, *
및 ?
패턴과 일치합니다.
Unless stated otherwise, “filename string” and “pattern string” either refer to
str
or ISO-8859-1
encoded bytes
objects. Note that the
functions documented below do not allow to mix a bytes
pattern with
a str
filename, and vice-versa.
Finally, note that functools.lru_cache()
with a maxsize of 32768
is used to cache the (typed) compiled regex patterns in the following
functions: fnmatch()
, fnmatchcase()
, filter()
.
- fnmatch.fnmatch(name, pat)¶
파일명 문자열 name이 패턴 문자열 pat와 일치하는지를 검사하여,
True
나False
를 반환합니다. 두 매개 변수는 모두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와 일치하는지를 검사하여,
True
나False
를 반환합니다; 비교는 대소 문자를 구분하며,os.path.normcase()
를 적용하지 않습니다.
- fnmatch.filter(names, pat)¶
패턴 문자열 pat와 일치하는 파일명 문자열의 이터러블 names의 요소로 리스트를 구축합니다.
[n for n in names if fnmatch(n, pat)]
과 같지만, 더 효율적으로 구현됩니다.
- fnmatch.filterfalse(names, pat)¶
Construct a list from those elements of the iterable of filename strings names that do not match the pattern string pat. It is the same as
[n for n in names if not fnmatch(n, pat)]
, but implemented more efficiently.Added in version 3.14.
- fnmatch.translate(pat)¶
셸 스타일의 패턴 pat를
re.match()
에서 사용하기 위해 정규식으로 변환한 값을 반환합니다. 패턴은str
일 것으로 기대합니다.예제:
>>> 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
유닉스 셸 스타일 경로 확장.