Debian Codegraph @

Doc/library/os.path.rst

raw
1 :mod:`!os.path` --- Common pathname manipulations
2 =================================================
3
4 .. module:: os.path
5 :synopsis: Operations on pathnames.
6
7 **Source code:** :source:`Lib/genericpath.py`, :source:`Lib/posixpath.py` (for POSIX) and
8 :source:`Lib/ntpath.py` (for Windows).
9
10 .. index:: single: path; operations
11
12 --------------
13
14 This module implements some useful functions on pathnames. To read or write
15 files see :func:`open`, and for accessing the filesystem see the :mod:`os`
16 module. The path parameters can be passed as strings, or bytes, or any object
17 implementing the :class:`os.PathLike` protocol.
18
19 Unlike a Unix shell, Python does not do any *automatic* path expansions.
20 Functions such as :func:`expanduser` and :func:`expandvars` can be invoked
21 explicitly when an application desires shell-like path expansion. (See also
22 the :mod:`glob` module.)
23
24
25 .. seealso::
26 The :mod:`pathlib` module offers high-level path objects.
27
28
29 .. note::
30
31 All of these functions accept either only bytes or only string objects as
32 their parameters. The result is an object of the same type, if a path or
33 file name is returned.
34
35 .. note::
36
37 Since different operating systems have different path name conventions, there
38 are several versions of this module in the standard library. The
39 :mod:`!os.path` module is always the path module suitable for the operating
40 system Python is running on, and therefore usable for local paths. However,
41 you can also import and use the individual modules if you want to manipulate
42 a path that is *always* in one of the different formats. They all have the
43 same interface:
44
45 * :mod:`!posixpath` for UNIX-style paths
46 * :mod:`!ntpath` for Windows paths
47
48
49 .. versionchanged:: 3.8
50
51 :func:`exists`, :func:`lexists`, :func:`isdir`, :func:`isfile`,
52 :func:`islink`, and :func:`ismount` now return ``False`` instead of
53 raising an exception for paths that contain characters or bytes
54 unrepresentable at the OS level.
55
56
57 .. function:: abspath(path)
58
59 Return a normalized absolutized version of the pathname *path*. On most
60 platforms, this is equivalent to calling ``normpath(join(os.getcwd(), path))``.
61
62 .. seealso:: :func:`os.path.join` and :func:`os.path.normpath`.
63
64 .. versionchanged:: 3.6
65 Accepts a :term:`path-like object`.
66
67
68 .. function:: basename(path, /)
69
70 Return the base name of pathname *path*. This is the second element of the
71 pair returned by passing *path* to the function :func:`split`. Note that
72 the result of this function is different
73 from the Unix :program:`basename` program; where :program:`basename` for
74 ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
75 empty string (``''``).
76
77 .. versionchanged:: 3.6
78 Accepts a :term:`path-like object`.
79
80
81 .. function:: commonpath(paths)
82
83 Return the longest common sub-path of each pathname in the iterable
84 *paths*. Raise :exc:`ValueError` if *paths* contain both absolute
85 and relative pathnames, if *paths* are on different drives, or
86 if *paths* is empty. Unlike :func:`commonprefix`, this returns a
87 valid path.
88
89 .. versionadded:: 3.5
90
91 .. versionchanged:: 3.6
92 Accepts a sequence of :term:`path-like objects <path-like object>`.
93
94 .. versionchanged:: 3.13
95 Any iterable can now be passed, rather than just sequences.
96
97
98 .. function:: commonprefix(list, /)
99
100 Return the longest string prefix (taken character-by-character) that is a
101 prefix of all strings in *list*. If *list* is empty, return the empty string
102 (``''``).
103
104 .. warning::
105
106 This function may return invalid paths because it works a
107 character at a time.
108 If you need a **common path prefix**, then the algorithm
109 implemented in this function is not secure. Use
110 :func:`commonpath` for finding a common path prefix.
111
112 ::
113
114 >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
115 '/usr/l'
116
117 >>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
118 '/usr'
119
120 .. versionchanged:: 3.6
121 Accepts a :term:`path-like object`.
122
123
124 .. function:: dirname(path, /)
125
126 Return the directory name of pathname *path*. This is the first element of
127 the pair returned by passing *path* to the function :func:`split`.
128
129 .. versionchanged:: 3.6
130 Accepts a :term:`path-like object`.
131
132
133 .. function:: exists(path)
134
135 Return ``True`` if *path* refers to an existing path or an open
136 file descriptor. Returns ``False`` for broken symbolic links. On
137 some platforms, this function may return ``False`` if permission is
138 not granted to execute :func:`os.stat` on the requested file, even
139 if the *path* physically exists.
140
141 .. versionchanged:: 3.3
142 *path* can now be an integer: ``True`` is returned if it is an
143 open file descriptor, ``False`` otherwise.
144
145 .. versionchanged:: 3.6
146 Accepts a :term:`path-like object`.
147
148
149 .. function:: lexists(path)
150
151 Return ``True`` if *path* refers to an existing path, including
152 broken symbolic links. Equivalent to :func:`exists` on platforms lacking
153 :func:`os.lstat`.
154
155 .. versionchanged:: 3.6
156 Accepts a :term:`path-like object`.
157
158
159 .. index:: single: ~ (tilde); home directory expansion
160
161 .. function:: expanduser(path)
162
163 On Unix and Windows, return the argument with an initial component of ``~`` or
164 ``~user`` replaced by that *user*'s home directory.
165
166 .. index:: pair: module; pwd
167
168 On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME`
169 if it is set; otherwise the current user's home directory is looked up in the
170 password directory through the built-in module :mod:`pwd`. An initial ``~user``
171 is looked up directly in the password directory.
172
173 On Windows, :envvar:`USERPROFILE` will be used if set, otherwise a combination
174 of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be used. An initial
175 ``~user`` is handled by checking that the last directory component of the current
176 user's home directory matches :envvar:`USERNAME`, and replacing it if so.
177
178 If the expansion fails or if the path does not begin with a tilde, the path is
179 returned unchanged.
180
181 .. versionchanged:: 3.6
182 Accepts a :term:`path-like object`.
183
184 .. versionchanged:: 3.8
185 No longer uses :envvar:`HOME` on Windows.
186
187 .. index::
188 single: $ (dollar); environment variables expansion
189 single: % (percent); environment variables expansion (Windows)
190
191 .. function:: expandvars(path)
192
193 Return the argument with environment variables expanded. Substrings of the form
194 ``$name`` or ``${name}`` are replaced by the value of environment variable
195 *name*. Malformed variable names and references to non-existing variables are
196 left unchanged.
197
198 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
199 ``${name}``.
200
201 .. versionchanged:: 3.6
202 Accepts a :term:`path-like object`.
203
204
205 .. function:: getatime(path, /)
206
207 Return the time of last access of *path*. The return value is a floating-point number giving
208 the number of seconds since the epoch (see the :mod:`time` module). Raise
209 :exc:`OSError` if the file does not exist or is inaccessible.
210
211
212 .. function:: getmtime(path, /)
213
214 Return the time of last modification of *path*. The return value is a floating-point number
215 giving the number of seconds since the epoch (see the :mod:`time` module).
216 Raise :exc:`OSError` if the file does not exist or is inaccessible.
217
218 .. versionchanged:: 3.6
219 Accepts a :term:`path-like object`.
220
221
222 .. function:: getctime(path, /)
223
224 Return the system's ctime which, on some systems (like Unix) is the time of the
225 last metadata change, and, on others (like Windows), is the creation time for *path*.
226 The return value is a number giving the number of seconds since the epoch (see
227 the :mod:`time` module). Raise :exc:`OSError` if the file does not exist or
228 is inaccessible.
229
230 .. versionchanged:: 3.6
231 Accepts a :term:`path-like object`.
232
233
234 .. function:: getsize(path, /)
235
236 Return the size, in bytes, of *path*. Raise :exc:`OSError` if the file does
237 not exist or is inaccessible.
238
239 .. versionchanged:: 3.6
240 Accepts a :term:`path-like object`.
241
242
243 .. function:: isabs(path, /)
244
245 Return ``True`` if *path* is an absolute pathname. On Unix, that means it
246 begins with a slash, on Windows that it begins with two (back)slashes, or a
247 drive letter, colon, and (back)slash together.
248
249 .. seealso:: :func:`abspath`
250
251 .. versionchanged:: 3.6
252 Accepts a :term:`path-like object`.
253
254 .. versionchanged:: 3.13
255 On Windows, returns ``False`` if the given path starts with exactly one
256 (back)slash.
257
258
259 .. function:: isfile(path)
260
261 Return ``True`` if *path* is an :func:`existing <exists>` regular file.
262 This follows symbolic links, so both :func:`islink` and :func:`isfile` can
263 be true for the same path.
264
265 .. versionchanged:: 3.6
266 Accepts a :term:`path-like object`.
267
268
269 .. function:: isdir(path, /)
270
271 Return ``True`` if *path* is an :func:`existing <exists>` directory. This
272 follows symbolic links, so both :func:`islink` and :func:`isdir` can be true
273 for the same path.
274
275 .. versionchanged:: 3.6
276 Accepts a :term:`path-like object`.
277
278
279 .. function:: isjunction(path)
280
281 Return ``True`` if *path* refers to an :func:`existing <lexists>` directory
282 entry that is a junction. Always return ``False`` if junctions are not
283 supported on the current platform.
284
285 .. versionadded:: 3.12
286
287
288 .. function:: islink(path)
289
290 Return ``True`` if *path* refers to an :func:`existing <exists>` directory
291 entry that is a symbolic link. Always ``False`` if symbolic links are not
292 supported by the Python runtime.
293
294 .. versionchanged:: 3.6
295 Accepts a :term:`path-like object`.
296
297
298 .. function:: ismount(path)
299
300 Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a
301 file system where a different file system has been mounted. On POSIX, the
302 function checks whether *path*'s parent, :file:`{path}/..`, is on a different
303 device than *path*, or whether :file:`{path}/..` and *path* point to the same
304 i-node on the same device --- this should detect mount points for all Unix
305 and POSIX variants. It is not able to reliably detect bind mounts on the
306 same filesystem. On Linux systems, it will always return ``True`` for btrfs
307 subvolumes, even if they aren't mount points. On Windows, a drive letter root
308 and a share UNC are always mount points, and for any other path
309 ``GetVolumePathName`` is called to see if it is different from the input path.
310
311 .. versionchanged:: 3.4
312 Added support for detecting non-root mount points on Windows.
313
314 .. versionchanged:: 3.6
315 Accepts a :term:`path-like object`.
316
317
318 .. function:: isdevdrive(path)
319
320 Return ``True`` if pathname *path* is located on a Windows Dev Drive.
321 A Dev Drive is optimized for developer scenarios, and offers faster
322 performance for reading and writing files. It is recommended for use for
323 source code, temporary build directories, package caches, and other
324 IO-intensive operations.
325
326 May raise an error for an invalid path, for example, one without a
327 recognizable drive, but returns ``False`` on platforms that do not support
328 Dev Drives. See `the Windows documentation <https://learn.microsoft.com/windows/dev-drive/>`_
329 for information on enabling and creating Dev Drives.
330
331 .. versionadded:: 3.12
332
333 .. versionchanged:: 3.13
334 The function is now available on all platforms, and will always return ``False`` on those that have no support for Dev Drives
335
336
337 .. function:: isreserved(path)
338
339 Return ``True`` if *path* is a reserved pathname on the current system.
340
341 On Windows, reserved filenames include those that end with a space or dot;
342 those that contain colons (i.e. file streams such as "name:stream"),
343 wildcard characters (i.e. ``'*?"<>'``), pipe, or ASCII control characters;
344 as well as DOS device names such as "NUL", "CON", "CONIN$", "CONOUT$",
345 "AUX", "PRN", "COM1", and "LPT1".
346
347 .. note::
348
349 This function approximates rules for reserved paths on most Windows
350 systems. These rules change over time in various Windows releases.
351 This function may be updated in future Python releases as changes to
352 the rules become broadly available.
353
354 .. availability:: Windows.
355
356 .. versionadded:: 3.13
357
358
359 .. function:: join(path, /, *paths)
360
361 Join one or more path segments intelligently. The return value is the
362 concatenation of *path* and all members of *\*paths*, with exactly one
363 directory separator following each non-empty part, except the last. That is,
364 the result will only end in a separator if the last part is either empty or
365 ends in a separator.
366
367 If a segment is an absolute path (which on Windows requires both a drive and
368 a root), then all previous segments are ignored and joining continues from the
369 absolute path segment. On Linux, for example::
370
371 >>> os.path.join('/home/foo', 'bar')
372 '/home/foo/bar'
373 >>> os.path.join('/home/foo', '/home/bar')
374 '/home/bar'
375
376 On Windows, the drive is not reset when a rooted path segment (e.g.,
377 ``r'\foo'``) is encountered. If a segment is on a different drive or is an
378 absolute path, all previous segments are ignored and the drive is reset. For
379 example::
380
381 >>> os.path.join('c:\\', 'foo')
382 'c:\\foo'
383 >>> os.path.join('c:\\foo', 'd:\\bar')
384 'd:\\bar'
385
386 Note that since there is a current directory for each drive,
387 ``os.path.join("c:", "foo")`` represents a path relative to the current
388 directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
389
390 .. versionchanged:: 3.6
391 Accepts a :term:`path-like object` for *path* and *paths*.
392
393
394 .. function:: normcase(path, /)
395
396 Normalize the case of a pathname. On Windows, convert all characters in the
397 pathname to lowercase, and also convert forward slashes to backward slashes.
398 On other operating systems, return the path unchanged.
399
400 .. versionchanged:: 3.6
401 Accepts a :term:`path-like object`.
402
403
404 .. function:: normpath(path)
405
406 Normalize a pathname by collapsing redundant separators and up-level
407 references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all
408 become ``A/B``. This string manipulation may change the meaning of a path
409 that contains symbolic links. On Windows, it converts forward slashes to
410 backward slashes. To normalize case, use :func:`normcase`.
411
412 .. note::
413 On POSIX systems, in accordance with `IEEE Std 1003.1 2013 Edition; 4.13
414 Pathname Resolution <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>`_,
415 if a pathname begins with exactly two slashes, the first component
416 following the leading characters may be interpreted in an implementation-defined
417 manner, although more than two leading characters shall be treated as a
418 single character.
419
420 .. versionchanged:: 3.6
421 Accepts a :term:`path-like object`.
422
423
424 .. function:: realpath(path, /, *, strict=False)
425
426 Return the canonical path of the specified filename, eliminating any symbolic
427 links encountered in the path (if they are supported by the operating
428 system). On Windows, this function will also resolve MS-DOS (also called 8.3)
429 style names such as ``C:\\PROGRA~1`` to ``C:\\Program Files``.
430
431 By default, the path is evaluated up to the first component that does not
432 exist, is a symlink loop, or whose evaluation raises :exc:`OSError`.
433 All such components are appended unchanged to the existing part of the path.
434
435 Some errors that are handled this way include "access denied", "not a
436 directory", or "bad argument to internal function". Thus, the
437 resulting path may be missing or inaccessible, may still contain
438 links or loops, and may traverse non-directories.
439
440 This behavior can be modified by keyword arguments:
441
442 If *strict* is ``True``, the first error encountered when evaluating the path is
443 re-raised.
444 In particular, :exc:`FileNotFoundError` is raised if *path* does not exist,
445 or another :exc:`OSError` if it is otherwise inaccessible.
446
447 If *strict* is :py:data:`os.path.ALLOW_MISSING`, errors other than
448 :exc:`FileNotFoundError` are re-raised (as with ``strict=True``).
449 Thus, the returned path will not contain any symbolic links, but the named
450 file and some of its parent directories may be missing.
451
452 .. note::
453 This function emulates the operating system's procedure for making a path
454 canonical, which differs slightly between Windows and UNIX with respect
455 to how links and subsequent path components interact.
456
457 Operating system APIs make paths canonical as needed, so it's not
458 normally necessary to call this function.
459
460 .. versionchanged:: 3.6
461 Accepts a :term:`path-like object`.
462
463 .. versionchanged:: 3.8
464 Symbolic links and junctions are now resolved on Windows.
465
466 .. versionchanged:: 3.10
467 The *strict* parameter was added.
468
469 .. versionchanged:: 3.14
470 The :py:data:`~os.path.ALLOW_MISSING` value for the *strict* parameter
471 was added.
472
473 .. data:: ALLOW_MISSING
474
475 Special value used for the *strict* argument in :func:`realpath`.
476
477 .. versionadded:: 3.14
478
479 .. function:: relpath(path, start=os.curdir)
480
481 Return a relative filepath to *path* either from the current directory or
482 from an optional *start* directory. This is a path computation: the
483 filesystem is not accessed to confirm the existence or nature of *path* or
484 *start*. On Windows, :exc:`ValueError` is raised when *path* and *start*
485 are on different drives.
486
487 *start* defaults to :data:`os.curdir`.
488
489 .. versionchanged:: 3.6
490 Accepts a :term:`path-like object`.
491
492
493 .. function:: samefile(path1, path2, /)
494
495 Return ``True`` if both pathname arguments refer to the same file or directory.
496 This is determined by the device number and i-node number and raises an
497 exception if an :func:`os.stat` call on either pathname fails.
498
499 .. versionchanged:: 3.2
500 Added Windows support.
501
502 .. versionchanged:: 3.4
503 Windows now uses the same implementation as all other platforms.
504
505 .. versionchanged:: 3.6
506 Accepts a :term:`path-like object`.
507
508
509 .. function:: sameopenfile(fp1, fp2)
510
511 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.
512
513 .. versionchanged:: 3.2
514 Added Windows support.
515
516 .. versionchanged:: 3.6
517 Accepts a :term:`path-like object`.
518
519
520 .. function:: samestat(stat1, stat2, /)
521
522 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
523 These structures may have been returned by :func:`os.fstat`,
524 :func:`os.lstat`, or :func:`os.stat`. This function implements the
525 underlying comparison used by :func:`samefile` and :func:`sameopenfile`.
526
527 .. versionchanged:: 3.4
528 Added Windows support.
529
530
531 .. function:: split(path, /)
532
533 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
534 last pathname component and *head* is everything leading up to that. The
535 *tail* part will never contain a slash; if *path* ends in a slash, *tail*
536 will be empty. If there is no slash in *path*, *head* will be empty. If
537 *path* is empty, both *head* and *tail* are empty. Trailing slashes are
538 stripped from *head* unless it is the root (one or more slashes only). In
539 all cases, ``join(head, tail)`` returns a path to the same location as *path*
540 (but the strings may differ). Also see the functions :func:`join`,
541 :func:`dirname` and :func:`basename`.
542
543 .. versionchanged:: 3.6
544 Accepts a :term:`path-like object`.
545
546
547 .. function:: splitdrive(path, /)
548
549 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
550 a mount point or the empty string. On systems which do not use drive
551 specifications, *drive* will always be the empty string. In all cases, ``drive
552 + tail`` will be the same as *path*.
553
554 On Windows, splits a pathname into drive/UNC sharepoint and relative path.
555
556 If the path contains a drive letter, drive will contain everything
557 up to and including the colon::
558
559 >>> splitdrive("c:/dir")
560 ("c:", "/dir")
561
562 If the path contains a UNC path, drive will contain the host name
563 and share::
564
565 >>> splitdrive("//host/computer/dir")
566 ("//host/computer", "/dir")
567
568 .. versionchanged:: 3.6
569 Accepts a :term:`path-like object`.
570
571
572 .. function:: splitroot(path, /)
573
574 Split the pathname *path* into a 3-item tuple ``(drive, root, tail)`` where
575 *drive* is a device name or mount point, *root* is a string of separators
576 after the drive, and *tail* is everything after the root. Any of these
577 items may be the empty string. In all cases, ``drive + root + tail`` will
578 be the same as *path*.
579
580 On POSIX systems, *drive* is always empty. The *root* may be empty (if *path* is
581 relative), a single forward slash (if *path* is absolute), or two forward slashes
582 (implementation-defined per `IEEE Std 1003.1-2017; 4.13 Pathname Resolution
583 <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>`_.)
584 For example::
585
586 >>> splitroot('/home/sam')
587 ('', '/', 'home/sam')
588 >>> splitroot('//home/sam')
589 ('', '//', 'home/sam')
590 >>> splitroot('///home/sam')
591 ('', '/', '//home/sam')
592
593 On Windows, *drive* may be empty, a drive-letter name, a UNC share, or a device
594 name. The *root* may be empty, a forward slash, or a backward slash. For
595 example::
596
597 >>> splitroot('C:/Users/Sam')
598 ('C:', '/', 'Users/Sam')
599 >>> splitroot('//Server/Share/Users/Sam')
600 ('//Server/Share', '/', 'Users/Sam')
601
602 .. versionadded:: 3.12
603
604
605 .. function:: splitext(path, /)
606
607 Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext ==
608 path``, and the extension, *ext*, is empty or begins with a period and contains at
609 most one period.
610
611 If the path contains no extension, *ext* will be ``''``::
612
613 >>> splitext('bar')
614 ('bar', '')
615
616 If the path contains an extension, then *ext* will be set to this extension,
617 including the leading period. Note that previous periods will be ignored::
618
619 >>> splitext('foo.bar.exe')
620 ('foo.bar', '.exe')
621 >>> splitext('/foo/bar.exe')
622 ('/foo/bar', '.exe')
623
624 Leading periods of the last component of the path are considered to
625 be part of the root::
626
627 >>> splitext('.cshrc')
628 ('.cshrc', '')
629 >>> splitext('/foo/....jpg')
630 ('/foo/....jpg', '')
631
632 .. versionchanged:: 3.6
633 Accepts a :term:`path-like object`.
634
635
636 .. data:: supports_unicode_filenames
637
638 ``True`` if arbitrary Unicode strings can be used as file names (within limitations
639 imposed by the file system).