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