Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(40675)

Delta Between Two Patch Sets: Doc/library/os.path.rst

Issue 10395: new os.path function to extract common prefix based on path components
Left Patch Set: Created 6 years, 11 months ago
Right Patch Set: Created 5 years, 3 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « no previous file | Lib/ntpath.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 :mod:`os.path` --- Common pathname manipulations 1 :mod:`os.path` --- Common pathname manipulations
2 ================================================ 2 ================================================
3 3
4 .. module:: os.path 4 .. module:: os.path
5 :synopsis: Operations on pathnames. 5 :synopsis: Operations on pathnames.
6 6
7 .. index:: single: path; operations 7 .. index:: single: path; operations
8 8
9 This module implements some useful functions on pathnames. To read or 9 This module implements some useful functions on pathnames. To read or
10 write files see :func:`open`, and for accessing the filesystem see the 10 write files see :func:`open`, and for accessing the filesystem see the
11 :mod:`os` module. The path parameters can be passed as either strings, 11 :mod:`os` module. The path parameters can be passed as either strings,
12 or bytes. Applications are encouraged to represent file names as 12 or bytes. Applications are encouraged to represent file names as
13 (Unicode) character strings. Unfortunately, some file names may not be 13 (Unicode) character strings. Unfortunately, some file names may not be
14 representable as strings on Unix, so applications that need to support 14 representable as strings on Unix, so applications that need to support
15 arbitrary file names on Unix should use bytes objects to represent 15 arbitrary file names on Unix should use bytes objects to represent
16 path names. Vice versa, using bytes objects cannot represent all file 16 path names. Vice versa, using bytes objects cannot represent all file
17 names on Windows (in the standard ``mbcs`` encoding), hence Windows 17 names on Windows (in the standard ``mbcs`` encoding), hence Windows
18 applications should use string objects to access all files. 18 applications should use string objects to access all files.
19 19
20 Unlike a unix shell, Python does not do any *automatic* path expansions.
21 Functions such as :func:`expanduser` and :func:`expandvars` can be invoked
22 explicitly when an application desires shell-like path expansion. (See also
23 the :mod:`glob` module.)
24
25
26 .. seealso::
27 The :mod:`pathlib` module offers high-level path objects.
28
29
20 .. note:: 30 .. note::
21 31
22 All of these functions accept either only bytes or only string objects as 32 All of these functions accept either only bytes or only string objects as
23 their parameters. The result is an object of the same type, if a path or 33 their parameters. The result is an object of the same type, if a path or
24 file name is returned. 34 file name is returned.
25 35
26 36
27 .. note:: 37 .. note::
28 38
29 Since different operating systems have different path name conventions, there 39 Since different operating systems have different path name conventions, there
30 are several versions of this module in the standard library. The 40 are several versions of this module in the standard library. The
31 :mod:`os.path` module is always the path module suitable for the operating 41 :mod:`os.path` module is always the path module suitable for the operating
32 system Python is running on, and therefore usable for local paths. However, 42 system Python is running on, and therefore usable for local paths. However,
33 you can also import and use the individual modules if you want to manipulate 43 you can also import and use the individual modules if you want to manipulate
34 a path that is *always* in one of the different formats. They all have the 44 a path that is *always* in one of the different formats. They all have the
35 same interface: 45 same interface:
36 46
37 * :mod:`posixpath` for UNIX-style paths 47 * :mod:`posixpath` for UNIX-style paths
38 * :mod:`ntpath` for Windows paths 48 * :mod:`ntpath` for Windows paths
39 * :mod:`macpath` for old-style MacOS paths 49 * :mod:`macpath` for old-style MacOS paths
40 50
41 51
42 .. function:: abspath(path) 52 .. function:: abspath(path)
43 53
44 Return a normalized absolutized version of the pathname *path*. On most 54 Return a normalized absolutized version of the pathname *path*. On most
45 platforms, this is equivalent to ``normpath(join(os.getcwd(), path))``. 55 platforms, this is equivalent to calling the function :func:`normpath` as
56 follows: ``normpath(join(os.getcwd(), path))``.
46 57
47 58
48 .. function:: basename(path) 59 .. function:: basename(path)
49 60
50 Return the base name of pathname *path*. This is the second half of the pair 61 Return the base name of pathname *path*. This is the second element of the
51 returned by ``split(path)``. Note that the result of this function is differ ent 62 pair returned by passing *path* to the function :func:`split`. Note that
63 the result of this function is different
52 from the Unix :program:`basename` program; where :program:`basename` for 64 from the Unix :program:`basename` program; where :program:`basename` for
53 ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an 65 ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
54 empty string (``''``). 66 empty string (``''``).
55 67
56 68
69 .. function:: commonpath(paths)
70
71 Return the longest common sub-path of each pathname in the sequence
72 *paths*. Raise ValueError if *paths* contains both absolute and relative
73 pathnames, or if *paths* is empty. Unlike :func:`commonprefix`, this
74 returns a valid path.
75
76 Availability: Unix, Windows
77
78 .. versionadded:: 3.5
79
80
57 .. function:: commonprefix(list) 81 .. function:: commonprefix(list)
58 82
59 Return the longest path prefix (taken character-by-character) that is a prefi x 83 Return the longest path prefix (taken character-by-character) that is a
60 of all paths in *list*. If *list* is empty, return the empty string (``''`` ). 84 prefix of all paths in *list*. If *list* is empty, return the empty string
61 Note that this may return invalid paths because it works a character at a tim e. 85 (``''``). Note that this may return invalid paths because it works a
62 86 character at a time. To obtain a valid path, see :func:`commonpath`.
63 .. function:: commonpath(paths)
64
65 Return the longest common sub-path of each pathname in the sequence
66 *paths*. The paths must be absolute, otherwise a ValueError is raised.
67 If *paths* is empty, return ``None``. If each path ends with a path
68 separator, the returned sub-path will also end with a separator, otherwise
69 it will not. Unlike :func:`commonprefix`, this returns a valid path.
70
71 Availability: Unix.
72
73 .. versionadded:: 3.4
74 87
75 88
76 .. function:: dirname(path) 89 .. function:: dirname(path)
77 90
78 Return the directory name of pathname *path*. This is the first half of the 91 Return the directory name of pathname *path*. This is the first element of
79 pair returned by ``split(path)``. 92 the pair returned by passing *path* to the function :func:`split`.
80 93
81 94
82 .. function:: exists(path) 95 .. function:: exists(path)
83 96
84 Return ``True`` if *path* refers to an existing path or an open 97 Return ``True`` if *path* refers to an existing path or an open
85 file descriptor. Returns ``False`` for broken symbolic links. On 98 file descriptor. Returns ``False`` for broken symbolic links. On
86 some platforms, this function may return ``False`` if permission is 99 some platforms, this function may return ``False`` if permission is
87 not granted to execute :func:`os.stat` on the requested file, even 100 not granted to execute :func:`os.stat` on the requested file, even
88 if the *path* physically exists. 101 if the *path* physically exists.
89 102
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
128 left unchanged. 141 left unchanged.
129 142
130 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and 143 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
131 ``${name}``. 144 ``${name}``.
132 145
133 146
134 .. function:: getatime(path) 147 .. function:: getatime(path)
135 148
136 Return the time of last access of *path*. The return value is a number givin g 149 Return the time of last access of *path*. The return value is a number givin g
137 the number of seconds since the epoch (see the :mod:`time` module). Raise 150 the number of seconds since the epoch (see the :mod:`time` module). Raise
138 :exc:`os.error` if the file does not exist or is inaccessible. 151 :exc:`OSError` if the file does not exist or is inaccessible.
139 152
140 If :func:`os.stat_float_times` returns True, the result is a floating point 153 If :func:`os.stat_float_times` returns ``True``, the result is a floating poi nt
141 number. 154 number.
142 155
143 156
144 .. function:: getmtime(path) 157 .. function:: getmtime(path)
145 158
146 Return the time of last modification of *path*. The return value is a number 159 Return the time of last modification of *path*. The return value is a number
147 giving the number of seconds since the epoch (see the :mod:`time` module). 160 giving the number of seconds since the epoch (see the :mod:`time` module).
148 Raise :exc:`os.error` if the file does not exist or is inaccessible. 161 Raise :exc:`OSError` if the file does not exist or is inaccessible.
149 162
150 If :func:`os.stat_float_times` returns True, the result is a floating point 163 If :func:`os.stat_float_times` returns ``True``, the result is a floating poi nt
151 number. 164 number.
152 165
153 166
154 .. function:: getctime(path) 167 .. function:: getctime(path)
155 168
156 Return the system's ctime which, on some systems (like Unix) is the time of t he 169 Return the system's ctime which, on some systems (like Unix) is the time of t he
157 last change, and, on others (like Windows), is the creation time for *path*. 170 last metadata change, and, on others (like Windows), is the creation time for *path*.
158 The return value is a number giving the number of seconds since the epoch (se e 171 The return value is a number giving the number of seconds since the epoch (se e
159 the :mod:`time` module). Raise :exc:`os.error` if the file does not exist o r 172 the :mod:`time` module). Raise :exc:`OSError` if the file does not exist or
160 is inaccessible. 173 is inaccessible.
161 174
162 175
163 .. function:: getsize(path) 176 .. function:: getsize(path)
164 177
165 Return the size, in bytes, of *path*. Raise :exc:`os.error` if the file does 178 Return the size, in bytes, of *path*. Raise :exc:`OSError` if the file does
166 not exist or is inaccessible. 179 not exist or is inaccessible.
167 180
168 181
169 .. function:: isabs(path) 182 .. function:: isabs(path)
170 183
171 Return ``True`` if *path* is an absolute pathname. On Unix, that means it 184 Return ``True`` if *path* is an absolute pathname. On Unix, that means it
172 begins with a slash, on Windows that it begins with a (back)slash after chopp ing 185 begins with a slash, on Windows that it begins with a (back)slash after chopp ing
173 off a potential drive letter. 186 off a potential drive letter.
174 187
175 188
176 .. function:: isfile(path) 189 .. function:: isfile(path)
177 190
178 Return ``True`` if *path* is an existing regular file. This follows symbolic 191 Return ``True`` if *path* is an existing regular file. This follows symbolic
179 links, so both :func:`islink` and :func:`isfile` can be true for the same pat h. 192 links, so both :func:`islink` and :func:`isfile` can be true for the same pat h.
180 193
181 194
182 .. function:: isdir(path) 195 .. function:: isdir(path)
183 196
184 Return ``True`` if *path* is an existing directory. This follows symbolic 197 Return ``True`` if *path* is an existing directory. This follows symbolic
185 links, so both :func:`islink` and :func:`isdir` can be true for the same path . 198 links, so both :func:`islink` and :func:`isdir` can be true for the same path .
186 199
187 200
188 .. function:: islink(path) 201 .. function:: islink(path)
189 202
190 Return ``True`` if *path* refers to a directory entry that is a symbolic link . 203 Return ``True`` if *path* refers to a directory entry that is a symbolic link .
191 Always ``False`` if symbolic links are not supported. 204 Always ``False`` if symbolic links are not supported by the python runtime.
192 205
193 206
194 .. function:: ismount(path) 207 .. function:: ismount(path)
195 208
196 Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a file 209 Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a
197 system where a different file system has been mounted. The function checks 210 file system where a different file system has been mounted. On POSIX, the
198 whether *path*'s parent, :file:`path/..`, is on a different device than *path *, 211 function checks whether *path*'s parent, :file:`path/..`, is on a different
199 or whether :file:`path/..` and *path* point to the same i-node on the same 212 device than *path*, or whether :file:`path/..` and *path* point to the same
200 device --- this should detect mount points for all Unix and POSIX variants. 213 i-node on the same device --- this should detect mount points for all Unix
214 and POSIX variants. On Windows, a drive letter root and a share UNC are
215 always mount points, and for any other path ``GetVolumePathName`` is called
216 to see if it is different from the input path.
217
218 .. versionadded:: 3.4
219 Support for detecting non-root mount points on Windows.
201 220
202 221
203 .. function:: join(path1[, path2[, ...]]) 222 .. function:: join(path1[, path2[, ...]])
204 223
205 Join one or more path components intelligently. If any component is an absol ute 224 Join one or more path components intelligently. If any component is an absol ute
206 path, all previous components (on Windows, including the previous drive lette r, 225 path, all previous components (on Windows, including the previous drive lette r,
207 if there was one) are thrown away, and joining continues. The return value i s 226 if there was one) are thrown away, and joining continues. The return value i s
208 the concatenation of *path1*, and optionally *path2*, etc., with exactly one 227 the concatenation of *path1*, and optionally *path2*, etc., with exactly one
209 directory separator (``os.sep``) following each non-empty part except the las t. 228 directory separator (``os.sep``) following each non-empty part except the las t.
210 (This means that an empty last part will result in a path that ends with a 229 (This means that an empty last part will result in a path that ends with a
211 separator.) Note that on Windows, since there is a current directory for 230 separator.) Note that on Windows, since there is a current directory for
212 each drive, ``os.path.join("c:", "foo")`` represents a path relative to the 231 each drive, ``os.path.join("c:", "foo")`` represents a path relative to the
213 current directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`. 232 current directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
214 233
215 234
216 .. function:: normcase(path) 235 .. function:: normcase(path)
217 236
218 Normalize the case of a pathname. On Unix and Mac OS X, this returns the 237 Normalize the case of a pathname. On Unix and Mac OS X, this returns the
219 path unchanged; on case-insensitive filesystems, it converts the path to 238 path unchanged; on case-insensitive filesystems, it converts the path to
220 lowercase. On Windows, it also converts forward slashes to backward slashes. 239 lowercase. On Windows, it also converts forward slashes to backward slashes.
221 Raise a TypeError if the type of *path* is not ``str`` or ``bytes``. 240 Raise a TypeError if the type of *path* is not ``str`` or ``bytes``.
222 241
223 242
224 .. function:: normpath(path) 243 .. function:: normpath(path)
225 244
226 Normalize a pathname. This collapses redundant separators and up-level 245 Normalize a pathname by collapsing redundant separators and up-level
227 references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all becom e 246 references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all
228 ``A/B``. 247 become ``A/B``. This string manipulation may change the meaning of a path
229 248 that contains symbolic links. On Windows, it converts forward slashes to
230 It does not normalize the case (use :func:`normcase` for that). On Windows, it 249 backward slashes. To normalize case, use :func:`normcase`.
231 converts forward slashes to backward slashes. It should be understood that th is
232 may change the meaning of the path if it contains symbolic links!
233 250
234 251
235 .. function:: realpath(path) 252 .. function:: realpath(path)
236 253
237 Return the canonical path of the specified filename, eliminating any symbolic 254 Return the canonical path of the specified filename, eliminating any symbolic
238 links encountered in the path (if they are supported by the operating system) . 255 links encountered in the path (if they are supported by the operating system) .
239 256
240 257
241 .. function:: relpath(path, start=None) 258 .. function:: relpath(path, start=os.curdir)
242 259
243 Return a relative filepath to *path* either from the current directory or fro m 260 Return a relative filepath to *path* either from the current directory or
244 an optional *start* point. 261 from an optional *start* directory. This is a path computation: the
262 filesystem is not accessed to confirm the existence or nature of *path* or
263 *start*.
245 264
246 *start* defaults to :attr:`os.curdir`. 265 *start* defaults to :attr:`os.curdir`.
247 266
248 Availability: Unix, Windows. 267 Availability: Unix, Windows.
249 268
250 269
251 .. function:: samefile(path1, path2) 270 .. function:: samefile(path1, path2)
252 271
253 Return ``True`` if both pathname arguments refer to the same file or director y. 272 Return ``True`` if both pathname arguments refer to the same file or director y.
254 On Unix, this is determined by the device number and i-node number and raises an 273 This is determined by the device number and i-node number and raises an
255 exception if a :func:`os.stat` call on either pathname fails. 274 exception if a :func:`os.stat` call on either pathname fails.
256
257 On Windows, two files are the same if they resolve to the same final path
258 name using the Windows API call GetFinalPathNameByHandle. This function
259 raises an exception if handles cannot be obtained to either file.
260 275
261 Availability: Unix, Windows. 276 Availability: Unix, Windows.
262 277
263 .. versionchanged:: 3.2 278 .. versionchanged:: 3.2
264 Added Windows support. 279 Added Windows support.
265 280
281 .. versionchanged:: 3.4
282 Windows now uses the same implementation as all other platforms.
283
266 284
267 .. function:: sameopenfile(fp1, fp2) 285 .. function:: sameopenfile(fp1, fp2)
268 286
269 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same fil e. 287 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same fil e.
270 288
271 Availability: Unix, Windows. 289 Availability: Unix, Windows.
272 290
273 .. versionchanged:: 3.2 291 .. versionchanged:: 3.2
274 Added Windows support. 292 Added Windows support.
275 293
276 294
277 .. function:: samestat(stat1, stat2) 295 .. function:: samestat(stat1, stat2)
278 296
279 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file . 297 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file .
280 These structures may have been returned by :func:`fstat`, :func:`lstat`, or 298 These structures may have been returned by :func:`os.fstat`,
281 :func:`stat`. This function implements the underlying comparison used by 299 :func:`os.lstat`, or :func:`os.stat`. This function implements the
282 :func:`samefile` and :func:`sameopenfile`. 300 underlying comparison used by :func:`samefile` and :func:`sameopenfile`.
283 301
284 Availability: Unix. 302 Availability: Unix, Windows.
303
304 .. versionchanged:: 3.4
305 Added Windows support.
285 306
286 307
287 .. function:: split(path) 308 .. function:: split(path)
288 309
289 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the 310 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
290 last pathname component and *head* is everything leading up to that. The 311 last pathname component and *head* is everything leading up to that. The
291 *tail* part will never contain a slash; if *path* ends in a slash, *tail* 312 *tail* part will never contain a slash; if *path* ends in a slash, *tail*
292 will be empty. If there is no slash in *path*, *head* will be empty. If 313 will be empty. If there is no slash in *path*, *head* will be empty. If
293 *path* is empty, both *head* and *tail* are empty. Trailing slashes are 314 *path* is empty, both *head* and *tail* are empty. Trailing slashes are
294 stripped from *head* unless it is the root (one or more slashes only). In 315 stripped from *head* unless it is the root (one or more slashes only). In
295 all cases, ``join(head, tail)`` returns a path to the same location as *path* 316 all cases, ``join(head, tail)`` returns a path to the same location as *path*
296 (but the strings may differ). 317 (but the strings may differ). Also see the functions :func:`dirname` and
318 :func:`basename`.
297 319
298 320
299 .. function:: splitdrive(path) 321 .. function:: splitdrive(path)
300 322
301 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is eith er 323 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is eith er
302 a mount point or the empty string. On systems which do not use drive 324 a mount point or the empty string. On systems which do not use drive
303 specifications, *drive* will always be the empty string. In all cases, ``dri ve 325 specifications, *drive* will always be the empty string. In all cases, ``dri ve
304 + tail`` will be the same as *path*. 326 + tail`` will be the same as *path*.
305 327
306 On Windows, splits a pathname into drive/UNC sharepoint and relative path. 328 On Windows, splits a pathname into drive/UNC sharepoint and relative path.
(...skipping 23 matching lines...) Expand all
330 Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UN C 352 Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UN C
331 mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of 353 mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of
332 the path (such as ``r'\path\file.ext'``). For paths containing drive letter s, 354 the path (such as ``r'\path\file.ext'``). For paths containing drive letter s,
333 *unc* will always be the empty string. 355 *unc* will always be the empty string.
334 356
335 Availability: Windows. 357 Availability: Windows.
336 358
337 359
338 .. data:: supports_unicode_filenames 360 .. data:: supports_unicode_filenames
339 361
340 True if arbitrary Unicode strings can be used as file names (within limitatio ns 362 ``True`` if arbitrary Unicode strings can be used as file names (within limit ations
341 imposed by the file system). 363 imposed by the file system).
LEFTRIGHT
« no previous file | Lib/ntpath.py » ('j') | Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Toggle Comments ('s')

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+