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

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, 8 months ago
Right Patch Set: Created 5 years 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
57 .. function:: commonpath(paths) 69 .. function:: commonpath(paths)
58 70
59 Return the longest common sub-path of each pathname in the sequence 71 Return the longest common sub-path of each pathname in the sequence
60 *paths*. Return ``None`` if *paths* contains both absolute and relative 72 *paths*. Raise ValueError if *paths* contains both absolute and relative
61 pathnames, or if *paths* is empty. Unlike :func:`commonprefix`, this 73 pathnames, or if *paths* is empty. Unlike :func:`commonprefix`, this
62 returns a valid path. 74 returns a valid path.
63 75
64 .. versionadded:: 3.4 76 Availability: Unix, Windows
77
78 .. versionadded:: 3.5
65 79
storchaka 2012/11/06 15:45:05 Availability: Unix, Windows. (It has not yet bee
eric.araujo 2012/11/06 16:20:32 Mac OS 9 hasn’t been supported for many versions (
storchaka 2012/11/06 16:54:49 See relpath(), samefile(), sameopenfile().
66 80
67 .. function:: commonprefix(list) 81 .. function:: commonprefix(list)
68 82
69 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
70 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
71 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
storchaka 2012/11/06 15:45:05 I think a reference to commonpath() will be useful
86 character at a time. To obtain a valid path, see :func:`commonpath`.
72 87
73 88
74 .. function:: dirname(path) 89 .. function:: dirname(path)
75 90
76 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
77 pair returned by ``split(path)``. 92 the pair returned by passing *path* to the function :func:`split`.
78 93
79 94
80 .. function:: exists(path) 95 .. function:: exists(path)
81 96
82 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
83 file descriptor. Returns ``False`` for broken symbolic links. On 98 file descriptor. Returns ``False`` for broken symbolic links. On
84 some platforms, this function may return ``False`` if permission is 99 some platforms, this function may return ``False`` if permission is
85 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
86 if the *path* physically exists. 101 if the *path* physically exists.
87 102
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
126 left unchanged. 141 left unchanged.
127 142
128 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and 143 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
129 ``${name}``. 144 ``${name}``.
130 145
131 146
132 .. function:: getatime(path) 147 .. function:: getatime(path)
133 148
134 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
135 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
136 :exc:`os.error` if the file does not exist or is inaccessible. 151 :exc:`OSError` if the file does not exist or is inaccessible.
137 152
138 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
139 number. 154 number.
140 155
141 156
142 .. function:: getmtime(path) 157 .. function:: getmtime(path)
143 158
144 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
145 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).
146 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.
147 162
148 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
149 number. 164 number.
150 165
151 166
152 .. function:: getctime(path) 167 .. function:: getctime(path)
153 168
154 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
155 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*.
156 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
157 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
158 is inaccessible. 173 is inaccessible.
159 174
160 175
161 .. function:: getsize(path) 176 .. function:: getsize(path)
162 177
163 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
164 not exist or is inaccessible. 179 not exist or is inaccessible.
165 180
166 181
167 .. function:: isabs(path) 182 .. function:: isabs(path)
168 183
169 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
170 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
171 off a potential drive letter. 186 off a potential drive letter.
172 187
173 188
174 .. function:: isfile(path) 189 .. function:: isfile(path)
175 190
176 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
177 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.
178 193
179 194
180 .. function:: isdir(path) 195 .. function:: isdir(path)
181 196
182 Return ``True`` if *path* is an existing directory. This follows symbolic 197 Return ``True`` if *path* is an existing directory. This follows symbolic
183 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 .
184 199
185 200
186 .. function:: islink(path) 201 .. function:: islink(path)
187 202
188 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 .
189 Always ``False`` if symbolic links are not supported. 204 Always ``False`` if symbolic links are not supported by the python runtime.
190 205
191 206
192 .. function:: ismount(path) 207 .. function:: ismount(path)
193 208
194 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
195 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
196 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
197 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
198 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.
199 220
200 221
201 .. function:: join(path1[, path2[, ...]]) 222 .. function:: join(path1[, path2[, ...]])
202 223
203 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
204 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,
205 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
206 the concatenation of *path1*, and optionally *path2*, etc., with exactly one 227 the concatenation of *path1*, and optionally *path2*, etc., with exactly one
207 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.
208 (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
209 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
210 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
211 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`.
212 233
213 234
214 .. function:: normcase(path) 235 .. function:: normcase(path)
215 236
216 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
217 path unchanged; on case-insensitive filesystems, it converts the path to 238 path unchanged; on case-insensitive filesystems, it converts the path to
218 lowercase. On Windows, it also converts forward slashes to backward slashes. 239 lowercase. On Windows, it also converts forward slashes to backward slashes.
219 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``.
220 241
221 242
222 .. function:: normpath(path) 243 .. function:: normpath(path)
223 244
224 Normalize a pathname. This collapses redundant separators and up-level 245 Normalize a pathname by collapsing redundant separators and up-level
225 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
226 ``A/B``. 247 become ``A/B``. This string manipulation may change the meaning of a path
227 248 that contains symbolic links. On Windows, it converts forward slashes to
228 It does not normalize the case (use :func:`normcase` for that). On Windows, it 249 backward slashes. To normalize case, use :func:`normcase`.
229 converts forward slashes to backward slashes. It should be understood that th is
230 may change the meaning of the path if it contains symbolic links!
231 250
232 251
233 .. function:: realpath(path) 252 .. function:: realpath(path)
234 253
235 Return the canonical path of the specified filename, eliminating any symbolic 254 Return the canonical path of the specified filename, eliminating any symbolic
236 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) .
237 256
238 257
239 .. function:: relpath(path, start=None) 258 .. function:: relpath(path, start=os.curdir)
240 259
241 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
242 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*.
243 264
244 *start* defaults to :attr:`os.curdir`. 265 *start* defaults to :attr:`os.curdir`.
245 266
246 Availability: Unix, Windows. 267 Availability: Unix, Windows.
247 268
248 269
249 .. function:: samefile(path1, path2) 270 .. function:: samefile(path1, path2)
250 271
251 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.
252 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
253 exception if a :func:`os.stat` call on either pathname fails. 274 exception if a :func:`os.stat` call on either pathname fails.
254
255 On Windows, two files are the same if they resolve to the same final path
256 name using the Windows API call GetFinalPathNameByHandle. This function
257 raises an exception if handles cannot be obtained to either file.
258 275
259 Availability: Unix, Windows. 276 Availability: Unix, Windows.
260 277
261 .. versionchanged:: 3.2 278 .. versionchanged:: 3.2
262 Added Windows support. 279 Added Windows support.
263 280
281 .. versionchanged:: 3.4
282 Windows now uses the same implementation as all other platforms.
283
264 284
265 .. function:: sameopenfile(fp1, fp2) 285 .. function:: sameopenfile(fp1, fp2)
266 286
267 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.
268 288
269 Availability: Unix, Windows. 289 Availability: Unix, Windows.
270 290
271 .. versionchanged:: 3.2 291 .. versionchanged:: 3.2
272 Added Windows support. 292 Added Windows support.
273 293
274 294
275 .. function:: samestat(stat1, stat2) 295 .. function:: samestat(stat1, stat2)
276 296
277 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 .
278 These structures may have been returned by :func:`fstat`, :func:`lstat`, or 298 These structures may have been returned by :func:`os.fstat`,
279 :func:`stat`. This function implements the underlying comparison used by 299 :func:`os.lstat`, or :func:`os.stat`. This function implements the
280 :func:`samefile` and :func:`sameopenfile`. 300 underlying comparison used by :func:`samefile` and :func:`sameopenfile`.
281 301
282 Availability: Unix. 302 Availability: Unix, Windows.
303
304 .. versionchanged:: 3.4
305 Added Windows support.
283 306
284 307
285 .. function:: split(path) 308 .. function:: split(path)
286 309
287 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
288 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
289 *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*
290 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
291 *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
292 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
293 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*
294 (but the strings may differ). 317 (but the strings may differ). Also see the functions :func:`dirname` and
318 :func:`basename`.
295 319
296 320
297 .. function:: splitdrive(path) 321 .. function:: splitdrive(path)
298 322
299 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
300 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
301 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
302 + tail`` will be the same as *path*. 326 + tail`` will be the same as *path*.
303 327
304 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
328 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
329 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
330 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,
331 *unc* will always be the empty string. 355 *unc* will always be the empty string.
332 356
333 Availability: Windows. 357 Availability: Windows.
334 358
335 359
336 .. data:: supports_unicode_filenames 360 .. data:: supports_unicode_filenames
337 361
338 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
339 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+