10.7. glob — Unix 风格路径名模式扩展

源代码: Lib/glob.py


The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. No tilde expansion is done, but * , ? ,和字符范围表达采用 [] 将被正确匹配。做到这是通过使用 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() )。

对于文字匹配,将元字符包裹在括号中。例如, '[?]' 匹配字符 '?' .

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. iglob ( pathname )

返回 iterator 产生相同值如 glob() 不用同时实际存储它们所有。

2.5 版新增。

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
Shell 样式文件名 (非路径) 扩展

上一话题

10.6. tempfile — 生成临时文件和目录

下一话题

10.8. fnmatch — Unix 文件名模式匹配

本页