Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`glob` --- Unix style pathname pattern expansion |
| 2 | ===================================================== |
| 3 | |
| 4 | .. module:: glob |
| 5 | :synopsis: Unix shell style pathname pattern expansion. |
| 6 | |
| 7 | |
| 8 | .. index:: single: filenames; pathname expansion |
| 9 | |
Raymond Hettinger | 1048094 | 2011-01-10 03:26:08 +0000 | [diff] [blame] | 10 | **Source code:** :source:`Lib/glob.py` |
| 11 | |
Raymond Hettinger | 4f707fd | 2011-01-10 19:54:11 +0000 | [diff] [blame] | 12 | -------------- |
| 13 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 14 | The :mod:`glob` module finds all the pathnames matching a specified pattern |
| 15 | according to the rules used by the Unix shell. No tilde expansion is done, but |
| 16 | ``*``, ``?``, and character ranges expressed with ``[]`` will be correctly |
| 17 | matched. This is done by using the :func:`os.listdir` and |
| 18 | :func:`fnmatch.fnmatch` functions in concert, and not by actually invoking a |
| 19 | subshell. (For tilde and shell variable expansion, use |
| 20 | :func:`os.path.expanduser` and :func:`os.path.expandvars`.) |
| 21 | |
| 22 | |
| 23 | .. function:: glob(pathname) |
| 24 | |
| 25 | Return a possibly-empty list of path names that match *pathname*, which must be |
| 26 | a string containing a path specification. *pathname* can be either absolute |
| 27 | (like :file:`/usr/src/Python-1.5/Makefile`) or relative (like |
| 28 | :file:`../../Tools/\*/\*.gif`), and can contain shell-style wildcards. Broken |
| 29 | symlinks are included in the results (as in the shell). |
| 30 | |
| 31 | |
| 32 | .. function:: iglob(pathname) |
| 33 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 34 | Return an :term:`iterator` which yields the same values as :func:`glob` |
| 35 | without actually storing them all simultaneously. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 36 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 37 | |
| 38 | For example, consider a directory containing only the following files: |
| 39 | :file:`1.gif`, :file:`2.txt`, and :file:`card.gif`. :func:`glob` will produce |
| 40 | the following results. Notice how any leading components of the path are |
| 41 | preserved. :: |
| 42 | |
| 43 | >>> import glob |
| 44 | >>> glob.glob('./[0-9].*') |
| 45 | ['./1.gif', './2.txt'] |
| 46 | >>> glob.glob('*.gif') |
| 47 | ['1.gif', 'card.gif'] |
| 48 | >>> glob.glob('?.gif') |
| 49 | ['1.gif'] |
| 50 | |
| 51 | |
| 52 | .. seealso:: |
| 53 | |
| 54 | Module :mod:`fnmatch` |
| 55 | Shell-style filename (not path) expansion |
| 56 | |