fnmatch


fnmatch 模块使用模式来匹配文件名.

模式语法和 Unix shell 中所使用的相同. 星号(*) 匹配零个或更多个字符, 问号(?) 匹配单个字符.

你也可以使用方括号来指定字符范围, 例如 [0-9] 代表一个数字. 其他所有字符都匹配它们本身.

import fnmatch
import os
for file in os.listdir("samples"):         # 逐行读取目录文件到file
    if fnmatch.fnmatch(file, "*.jpg"):   # 判断输入文件是否符合*.jpg标准,如果符合则输出
        print file
sample.jpg

glob 和 find 模块在内部使用 fnmatch 模块来实现.


>>>names = ['dlsf', 'ewro.txt', 'te.py', 'youe.py']  
#匹配以.py结尾的字符  
>>> fnmatch.filter(names, '*.py')  
>>> ['te.py', 'youe.py']  
  
>>> fnmatch.filter(names, '[de]')  
>>> []  
#匹配以d或e开头的字符  
>>>fnmatch.filter(names, '[de]*')  
>>>['dlsf', 'ewro.txt']


你可能感兴趣的:(fnmatch)