Fred Drake | 3a0351c | 1998-04-04 07:23:21 +0000 | [diff] [blame] | 1 | \section{Standard Module \module{glob}} |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 2 | \label{module-glob} |
Guido van Rossum | e6d579d | 1997-03-25 22:07:53 +0000 | [diff] [blame] | 3 | \stmodindex{glob} |
Guido van Rossum | e6d579d | 1997-03-25 22:07:53 +0000 | [diff] [blame] | 4 | |
Fred Drake | ad51192 | 1998-02-16 21:25:53 +0000 | [diff] [blame] | 5 | The \module{glob} module finds all the pathnames matching a specified |
Guido van Rossum | e6d579d | 1997-03-25 22:07:53 +0000 | [diff] [blame] | 6 | pattern according to the rules used by the \UNIX{} shell. No tilde |
Fred Drake | 45c9df6 | 1997-12-29 15:55:10 +0000 | [diff] [blame] | 7 | expansion is done, but \code{*}, \code{?}, and character ranges |
| 8 | expressed with \code{[]} will be correctly matched. This is done by |
Fred Drake | ad51192 | 1998-02-16 21:25:53 +0000 | [diff] [blame] | 9 | using the \function{os.listdir()} and \function{fnmatch.fnmatch()} |
| 10 | functions in concert, and not by actually invoking a subshell. (For |
| 11 | tilde and shell variable expansion, use \function{os.path.expanduser()} |
| 12 | and \function{os.path.expandvars()}.) |
Guido van Rossum | e6d579d | 1997-03-25 22:07:53 +0000 | [diff] [blame] | 13 | |
| 14 | \begin{funcdesc}{glob}{pathname} |
| 15 | Returns a possibly-empty list of path names that match \var{pathname}, |
| 16 | which must be a string containing a path specification. |
| 17 | \var{pathname} can be either absolute (like |
Fred Drake | 2de75ec | 1998-04-09 14:12:11 +0000 | [diff] [blame] | 18 | \file{/usr/src/Python-1.5/Makefile}) or relative (like |
Guido van Rossum | e6d579d | 1997-03-25 22:07:53 +0000 | [diff] [blame] | 19 | \file{../../Tools/*.gif}), and can contain shell-style wildcards. |
| 20 | \end{funcdesc} |
| 21 | |
| 22 | For example, consider a directory containing only the following files: |
Fred Drake | 5bfe485 | 1998-04-03 06:14:54 +0000 | [diff] [blame] | 23 | \file{1.gif}, \file{2.txt}, and \file{card.gif}. \function{glob()} |
Guido van Rossum | e6d579d | 1997-03-25 22:07:53 +0000 | [diff] [blame] | 24 | will produce the following results. Notice how any leading components |
| 25 | of the path are preserved. |
| 26 | |
Fred Drake | 1947991 | 1998-02-13 06:58:54 +0000 | [diff] [blame] | 27 | \begin{verbatim} |
Guido van Rossum | e6d579d | 1997-03-25 22:07:53 +0000 | [diff] [blame] | 28 | >>> import glob |
| 29 | >>> glob.glob('./[0-9].*') |
| 30 | ['./1.gif', './2.txt'] |
| 31 | >>> glob.glob('*.gif') |
| 32 | ['1.gif', 'card.gif'] |
| 33 | >>> glob.glob('?.gif') |
| 34 | ['1.gif'] |
Fred Drake | 1947991 | 1998-02-13 06:58:54 +0000 | [diff] [blame] | 35 | \end{verbatim} |