pathlib库Path函数_通配符查找文件

pathlib库从Python3.6开始用,目的是替换原有的os.path()函数。其中Path函数用于处理文件路径。本文记录一些通配符查找文件的简单用法。

(本例基于Python Console操作演示,可根据开发环境进入Python Console测试代码)


导包

>>> from pathlib import Path

通配符查找

>>> p = Path('C:/Users')

>>> list(p.glob('*')) # *号查找目录下所有内容,包括文件、文件夹

[WindowsPath('C:/Users/17676'), WindowsPath('C:/Users/All Users'), WindowsPath('C:/Users/Default'), WindowsPath('C:/Users/Default User'), WindowsPath('C:/Users/desktop.ini'), WindowsPath('C:/Users/Public')]

>>> list(p.glob('*.ini')) # 列出对应ini后缀的文件

[WindowsPath('C:/Users/desktop.ini')]

>>> list(p.glob('D?fault*')) # 这里?表示一个字符,*表示任意个字符

[WindowsPath('C:/Users/Default'), WindowsPath('C:/Users/Default User')]


补充说明

glob方法类似于正则表达式,可以灵活匹配文件名。返回列表结果,可进一步使用for循环操作。