glob
— Unix 风格路径名模式扩展
¶
源代码: Lib/glob.py
The
glob
模块根据 Unix Shell 使用规则,查找匹配指定模式的所有路径名,尽管结果以任意次序返回。不展开 ~,但
*
,
?
,和字符范围表达采用
[]
将被正确匹配。做到这是通过使用
os.scandir()
and
fnmatch.fnmatch()
函数一致,而不是通过援引子 Shell。
注意,文件开头采用点 (
.
) 只能匹配也以点开头的模式,不像
fnmatch.fnmatch()
or
pathlib.Path.glob()
。(为展开 ~ 和 Shell 变量,使用
os.path.expanduser()
and
os.path.expandvars()
)。
对于文字匹配,将元字符包裹在括号中。例如,
'[?]'
匹配字符
'?'
.
The
glob
模块定义了下列函数:
- glob. glob ( pathname , * , root_dir = None , dir_fd = None , recursive = False , include_hidden = False ) ¶
-
返回可能为空的路径名列表匹配 pathname ,必须是包含路径规范的字符串。 pathname 可以是绝对的 (像
/usr/src/Python-1.5/Makefile) 或相对的 (像../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell). Whether or not the results are sorted depends on the file system. If a file that satisfies conditions is removed or added during the call of this function, whether a path name for that file will be included is unspecified.若 root_dir 不是
None,它应该是 像路径对象 指定要搜索的根目录。它有相同效果对于glob()如在调用它之前改变当前目录。若 pathname 是相对的,结果包含的路径将相对于 root_dir .此函数可以支持 相对于目录描述符的路径 采用 dir_fd 参数。
若 recursive 为 True,模式
**将匹配任何文件、零个或多个目录、子目录及到目录的符号链接。若模式之后紧跟os.seporos.altsep那么将不匹配文件。若 include_hidden 为 True,
**模式将匹配隐藏目录。引发 审计事件
glob.glob采用自变量pathname,recursive.引发 审计事件
glob.glob/2采用自变量pathname,recursive,root_dir,dir_fd.注意
使用
**模式在大型目录树中可能消耗过多时间。注意
This function may return duplicate path names if pathname contains multiple “
**” patterns and recursive 为 True。3.5 版改变: 支持递归 glob 使用
**。3.10 版改变: 添加 root_dir and dir_fd 参数。
3.11 版改变: 添加 include_hidden 参数。
- glob. iglob ( pathname , * , root_dir = None , dir_fd = None , recursive = False , include_hidden = False ) ¶
-
返回 iterator 产生相同值如
glob()不用同时实际存储它们所有。引发 审计事件
glob.glob采用自变量pathname,recursive.引发 审计事件
glob.glob/2采用自变量pathname,recursive,root_dir,dir_fd.注意
This function may return duplicate path names if pathname contains multiple “
**” patterns and recursive 为 True。3.5 版改变: 支持递归 glob 使用
**。3.10 版改变: 添加 root_dir and dir_fd 参数。
3.11 版改变: 添加 include_hidden 参数。
- glob. escape ( pathname ) ¶
-
转义所有特殊字符 (
'?','*'and'[')。这很有用,若想要匹配其中可能拥有特殊字符的任意文字字符串。不转义在 "驱动器/UNC" 共享点中的特殊字符,如在 Windowsescape('//?/c:/Quo vadis?.txt')返回'//?/c:/Quo vadis[?].txt'.Added in version 3.4.