Debian Codegraph @

Doc/library/glob.rst

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