This document is for an old version of Python that is no longer supported. You should upgrade and read the Python 当前稳定版本的文档.

# 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, although results are returned in arbitrary order. No tilde expansion is done, but `*`, `?`, and character ranges expressed with `[]` will be correctly matched. This is done by using the `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`)，并且可包含 shell 风格的通配符。 无效的符号链接可以包含在结果中 (与在 shell 中一样)。

`glob.``iglob`(pathname)

  返回一个 iterator，它会产生与 `glob()` 相同的结果，但不会实际地同时保存它们。

  2.5 新版功能.

For example, consider a directory containing only the following files: `1.gif`, `2.txt`, and `card.gif`. `glob()` will produce the following results. Notice how any leading components of the path are preserved.

    >>> import glob
    >>> glob.glob('./[0-9].*')
    ['./1.gif', './2.txt']
    >>> glob.glob('*.gif')
    ['1.gif', 'card.gif']
    >>> glob.glob('?.gif')
    ['1.gif']

如果目录包含以 `.` 打头的文件，它们默认将不会被匹配。 例如，考虑一个包含 `card.gif` 和 `.card.gif` 的目录:

    >>> import glob
    >>> glob.glob('*.gif')
    ['card.gif']
    >>> glob.glob('.c*')
    ['.card.gif']

参见

模块 `fnmatch`

  Shell 风格文件名（而非路径）扩展