python--fnmatch

import fnmatch
'''
这个库专门是用来做文件名匹配的,可以使用通配符如下
* 匹配任何数量的任意字符
? 匹配单个数量的任意字符
[seq] 匹配seq中的任意字符
[!seq] 匹配除sql以外的字符

里面的方法主要介绍两个:fnmatch和filter
'''
print(fnmatch.fnmatch("12.txt", "1?txt"))  # False
print(fnmatch.fnmatch("12.txt", "1??txt"))  # True

# 虽然是用来匹配文件名的,但是其他字符串也一样可以匹配
print(fnmatch.fnmatch("i love satori", "*satori"))  # True
print(fnmatch.fnmatch("koishi", "[ko][!i]ishi"))  # True


# fnmatch是用来单个匹配的,返回True or False
# filter则可以传入一个列表,直接返回匹配成功的结果
print(fnmatch.filter(["a.txt", "a.png", "a.jpg", "a.py"], "a.??g"))  # ['a.png', 'a.jpg']

# 之所以介绍这个模块,是为了匹配字符串的,不是用来匹配文件名的
# 如果是遍历文件需要文件名的话,直接使用glob即可,功能更加强大。

  

猜你喜欢

转载自www.cnblogs.com/traditional/p/9978730.html