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 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, "``**``" pattern will match hidden directories.
74
75 .. audit-event:: glob.glob pathname,recursive glob.glob
76 .. audit-event:: glob.glob/2 pathname,recursive,root_dir,dir_fd glob.glob
77
78 .. note::
79 Using the "``**``" pattern in large directory trees may consume
80 an inordinate amount of time.
81
82 .. note::
83 This function may return duplicate path names if *pathname*
84 contains multiple "``**``" patterns and *recursive* is true.
85
86 .. note::
87 Any :exc:`OSError` exceptions raised from scanning the filesystem are
88 suppressed. This includes :exc:`PermissionError` when accessing
89 directories without read permission.
90
91 .. versionchanged:: 3.5
92 Support for recursive globs using "``**``".
93
94 .. versionchanged:: 3.10
95 Added the *root_dir* and *dir_fd* parameters.
96
97 .. versionchanged:: 3.11
98 Added the *include_hidden* parameter.
99
100
101 .. function:: iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False, \
102 include_hidden=False)
103
104 Return an :term:`iterator` which yields the same values as :func:`glob`
105 without actually storing them all simultaneously.
106
107 .. audit-event:: glob.glob pathname,recursive glob.iglob
108 .. audit-event:: glob.glob/2 pathname,recursive,root_dir,dir_fd glob.iglob
109
110 .. note::
111 This function may return duplicate path names if *pathname*
112 contains multiple "``**``" patterns and *recursive* is true.
113
114 .. note::
115 Any :exc:`OSError` exceptions raised from scanning the filesystem are
116 suppressed. This includes :exc:`PermissionError` when accessing
117 directories without read permission.
118
119 .. versionchanged:: 3.5
120 Support for recursive globs using "``**``".
121
122 .. versionchanged:: 3.10
123 Added the *root_dir* and *dir_fd* parameters.
124
125 .. versionchanged:: 3.11
126 Added the *include_hidden* parameter.
127
128
129 .. function:: escape(pathname)
130
131 Escape all special characters (``'?'``, ``'*'`` and ``'['``).
132 This is useful if you want to match an arbitrary literal string that may
133 have special characters in it. Special characters in drive/UNC
134 sharepoints are not escaped, e.g. on Windows
135 ``escape('//?/c:/Quo vadis?.txt')`` returns ``'//?/c:/Quo vadis[?].txt'``.
136
137 .. versionadded:: 3.4
138
139
140 .. function:: translate(pathname, *, recursive=False, include_hidden=False, seps=None)
141
142 Convert the given path specification to a regular expression for use with
143 :func:`re.match`. The path specification can contain shell-style wildcards.
144
145 For example:
146
147 >>> import glob, re
148 >>>
149 >>> regex = glob.translate('**/*.txt', recursive=True, include_hidden=True)
150 >>> regex
151 '(?s:(?:.+/)?[^/]*\\.txt)\\z'
152 >>> reobj = re.compile(regex)
153 >>> reobj.match('foo/bar/baz.txt')
154 <re.Match object; span=(0, 15), match='foo/bar/baz.txt'>
155
156 Path separators and segments are meaningful to this function, unlike
157 :func:`fnmatch.translate`. By default wildcards do not match path
158 separators, and ``*`` pattern segments match precisely one path segment.
159
160 If *recursive* is true, the pattern segment "``**``" will match any number
161 of path segments.
162
163 If *include_hidden* is true, wildcards can match path segments that start
164 with a dot (``.``).
165
166 A sequence of path separators may be supplied to the *seps* argument. If
167 not given, :data:`os.sep` and :data:`~os.altsep` (if available) are used.
168
169 .. seealso::
170
171 :meth:`pathlib.PurePath.full_match` and :meth:`pathlib.Path.glob`
172 methods, which call this function to implement pattern matching and
173 globbing.
174
175 .. versionadded:: 3.13
176
177
178 Examples
179 --------
180
181 Consider a directory containing the following files:
182 :file:`1.gif`, :file:`2.txt`, :file:`card.gif` and a subdirectory :file:`sub`
183 which contains only the file :file:`3.txt`. :func:`glob` will produce
184 the following results. Notice how any leading components of the path are
185 preserved. ::
186
187 >>> import glob
188 >>> glob.glob('./[0-9].*')
189 ['./1.gif', './2.txt']
190 >>> glob.glob('*.gif')
191 ['1.gif', 'card.gif']
192 >>> glob.glob('?.gif')
193 ['1.gif']
194 >>> glob.glob('**/*.txt', recursive=True)
195 ['2.txt', 'sub/3.txt']
196 >>> glob.glob('./**/', recursive=True)
197 ['./', './sub/']
198
199 If the directory contains files starting with ``.`` they won't be matched by
200 default. For example, consider a directory containing :file:`card.gif` and
201 :file:`.card.gif`::
202
203 >>> import glob
204 >>> glob.glob('*.gif')
205 ['card.gif']
206 >>> glob.glob('.c*')
207 ['.card.gif']
208
209 .. seealso::
210 The :mod:`fnmatch` module offers shell-style filename (not path) expansion.
211
212 .. seealso::
213 The :mod:`pathlib` module offers high-level path objects.