• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`!glob` --- Unix style pathname pattern expansion
2======================================================
3
4.. module:: glob
5   :synopsis: Unix shell style pathname pattern expansion.
6
7**Source code:** :source:`Lib/glob.py`
8
9.. index:: single: filenames; pathname expansion
10
11--------------
12
13.. index::
14   single: * (asterisk); in glob-style wildcards
15   single: ? (question mark); in glob-style wildcards
16   single: [] (square brackets); in glob-style wildcards
17   single: ! (exclamation); in glob-style wildcards
18   single: - (minus); in glob-style wildcards
19   single: . (dot); in glob-style wildcards
20
21The :mod:`glob` module finds all the pathnames matching a specified pattern
22according to the rules used by the Unix shell, although results are returned in
23arbitrary order.  No tilde expansion is done, but ``*``, ``?``, and character
24ranges expressed with ``[]`` will be correctly matched.  This is done by using
25the :func:`os.scandir` and :func:`fnmatch.fnmatch` functions in concert, and
26not by actually invoking a subshell.
27
28Note that files beginning with a dot (``.``) can only be matched by
29patterns that also start with a dot,
30unlike :func:`fnmatch.fnmatch` or :func:`pathlib.Path.glob`.
31(For tilde and shell variable expansion, use :func:`os.path.expanduser` and
32:func:`os.path.expandvars`.)
33
34For a literal match, wrap the meta-characters in brackets.
35For example, ``'[?]'`` matches the character ``'?'``.
36
37The :mod:`glob` module defines the following functions:
38
39
40.. function:: glob(pathname, *, root_dir=None, dir_fd=None, recursive=False, \
41                   include_hidden=False)
42
43   Return a possibly empty list of path names that match *pathname*, which must be
44   a string containing a path specification. *pathname* can be either absolute
45   (like :file:`/usr/src/Python-1.5/Makefile`) or relative (like
46   :file:`../../Tools/\*/\*.gif`), and can contain shell-style wildcards. Broken
47   symlinks are included in the results (as in the shell). Whether or not the
48   results are sorted depends on the file system.  If a file that satisfies
49   conditions is removed or added during the call of this function, whether
50   a path name for that file will be included is unspecified.
51
52   If *root_dir* is not ``None``, it should be a :term:`path-like object`
53   specifying the root directory for searching.  It has the same effect on
54   :func:`glob` as changing the current directory before calling it.  If
55   *pathname* is relative, the result will contain paths relative to
56   *root_dir*.
57
58   This function can support :ref:`paths relative to directory descriptors
59   <dir_fd>` with the *dir_fd* parameter.
60
61   .. index::
62      single: **; in glob-style wildcards
63
64   If *recursive* is true, the pattern "``**``" will match any files and zero or
65   more directories, subdirectories and symbolic links to directories. If the
66   pattern is followed by an :data:`os.sep` or :data:`os.altsep` then files will not
67   match.
68
69   If *include_hidden* is true, "``**``" pattern will match hidden directories.
70
71   .. audit-event:: glob.glob pathname,recursive glob.glob
72   .. audit-event:: glob.glob/2 pathname,recursive,root_dir,dir_fd glob.glob
73
74   .. note::
75      Using the "``**``" pattern in large directory trees may consume
76      an inordinate amount of time.
77
78   .. note::
79      This function may return duplicate path names if *pathname*
80      contains multiple "``**``" patterns and *recursive* is true.
81
82   .. versionchanged:: 3.5
83      Support for recursive globs using "``**``".
84
85   .. versionchanged:: 3.10
86      Added the *root_dir* and *dir_fd* parameters.
87
88   .. versionchanged:: 3.11
89      Added the *include_hidden* parameter.
90
91
92.. function:: iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False, \
93                    include_hidden=False)
94
95   Return an :term:`iterator` which yields the same values as :func:`glob`
96   without actually storing them all simultaneously.
97
98   .. audit-event:: glob.glob pathname,recursive glob.iglob
99   .. audit-event:: glob.glob/2 pathname,recursive,root_dir,dir_fd glob.iglob
100
101   .. note::
102      This function may return duplicate path names if *pathname*
103      contains multiple "``**``" patterns and *recursive* is true.
104
105   .. versionchanged:: 3.5
106      Support for recursive globs using "``**``".
107
108   .. versionchanged:: 3.10
109      Added the *root_dir* and *dir_fd* parameters.
110
111   .. versionchanged:: 3.11
112      Added the *include_hidden* parameter.
113
114
115.. function:: escape(pathname)
116
117   Escape all special characters (``'?'``, ``'*'`` and ``'['``).
118   This is useful if you want to match an arbitrary literal string that may
119   have special characters in it.  Special characters in drive/UNC
120   sharepoints are not escaped, e.g. on Windows
121   ``escape('//?/c:/Quo vadis?.txt')`` returns ``'//?/c:/Quo vadis[?].txt'``.
122
123   .. versionadded:: 3.4
124
125
126.. function:: translate(pathname, *, recursive=False, include_hidden=False, seps=None)
127
128   Convert the given path specification to a regular expression for use with
129   :func:`re.match`. The path specification can contain shell-style wildcards.
130
131   For example:
132
133      >>> import glob, re
134      >>>
135      >>> regex = glob.translate('**/*.txt', recursive=True, include_hidden=True)
136      >>> regex
137      '(?s:(?:.+/)?[^/]*\\.txt)\\Z'
138      >>> reobj = re.compile(regex)
139      >>> reobj.match('foo/bar/baz.txt')
140      <re.Match object; span=(0, 15), match='foo/bar/baz.txt'>
141
142   Path separators and segments are meaningful to this function, unlike
143   :func:`fnmatch.translate`. By default wildcards do not match path
144   separators, and ``*`` pattern segments match precisely one path segment.
145
146   If *recursive* is true, the pattern segment "``**``" will match any number
147   of path segments.
148
149   If *include_hidden* is true, wildcards can match path segments that start
150   with a dot (``.``).
151
152   A sequence of path separators may be supplied to the *seps* argument. If
153   not given, :data:`os.sep` and :data:`~os.altsep` (if available) are used.
154
155   .. seealso::
156
157     :meth:`pathlib.PurePath.full_match` and :meth:`pathlib.Path.glob`
158     methods, which call this function to implement pattern matching and
159     globbing.
160
161   .. versionadded:: 3.13
162
163
164Examples
165--------
166
167Consider a directory containing the following files:
168:file:`1.gif`, :file:`2.txt`, :file:`card.gif` and a subdirectory :file:`sub`
169which contains only the file :file:`3.txt`.  :func:`glob` will produce
170the following results.  Notice how any leading components of the path are
171preserved. ::
172
173   >>> import glob
174   >>> glob.glob('./[0-9].*')
175   ['./1.gif', './2.txt']
176   >>> glob.glob('*.gif')
177   ['1.gif', 'card.gif']
178   >>> glob.glob('?.gif')
179   ['1.gif']
180   >>> glob.glob('**/*.txt', recursive=True)
181   ['2.txt', 'sub/3.txt']
182   >>> glob.glob('./**/', recursive=True)
183   ['./', './sub/']
184
185If the directory contains files starting with ``.`` they won't be matched by
186default. For example, consider a directory containing :file:`card.gif` and
187:file:`.card.gif`::
188
189   >>> import glob
190   >>> glob.glob('*.gif')
191   ['card.gif']
192   >>> glob.glob('.c*')
193   ['.card.gif']
194
195.. seealso::
196   The :mod:`fnmatch` module offers shell-style filename (not path) expansion.
197
198.. seealso::
199   The :mod:`pathlib` module offers high-level path objects.
200