glob
— Unix 风格路径名模式扩展
¶
源代码: Lib/glob.py
The
glob
模块根据 Unix Shell 使用规则,查找匹配指定模式的所有路径名,尽管结果以任意次序返回。不展开 ~,但
*
,
?
,和字符范围表达采用
[]
将被正确匹配。做到这是通过使用
os.listdir()
and
fnmatch.fnmatch()
functions in concert, and not by actually invoking a subshell. Note that unlike
fnmatch.fnmatch()
,
glob
treats filenames beginning with a dot (
.
) as special cases. (For tilde and shell variable expansion, use
os.path.expanduser()
and
os.path.expandvars()
)。
对于文字匹配,将元字符包裹在括号中。例如,
'[?]'
匹配字符
'?'
.
另请参阅
The
pathlib
模块提供高级路径对象。
glob.
glob
(
pathname
)
¶
返回的路径名列表 (可能为空) 匹配它也被替换为
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).
glob.
escape
(
pathname
)
¶
转义所有特殊字符 (
'?'
,
'*'
and
'['
)。这很有用,若想要匹配其中可能拥有特殊字符的任意文字字符串。不转义在 "驱动器/UNC" 共享点中的特殊字符,如在 Windows
escape('//?/c:/Quo vadis?.txt')
返回
'//?/c:/Quo vadis[?].txt'
.
3.4 版新增。
For example, consider a directory containing only the following files:
1.gif
,
2.txt
,和
card.gif
.
glob()
将产生下列结果。预告,如何预留路径的任何前导分量。
>>> import glob >>> glob.glob('./[0-9].*') ['./1.gif', './2.txt'] >>> glob.glob('*.gif') ['1.gif', 'card.gif'] >>> glob.glob('?.gif') ['1.gif']
若目录包含的文件开头采用
.
,默认情况下不会匹配它们。例如,考虑目录包含
card.gif
and
.card.gif
:
>>> import glob >>> glob.glob('*.gif') ['card.gif'] >>> glob.glob('.c*') ['.card.gif']
另请参阅
fnmatch