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