1:mod:`os.path` --- Common pathname manipulations 2================================================ 3 4.. module:: os.path 5 :synopsis: Operations on pathnames. 6 7**Source code:** :source:`Lib/posixpath.py` (for POSIX) and 8:source:`Lib/ntpath.py` (for Windows). 9 10.. index:: single: path; operations 11 12-------------- 13 14This module implements some useful functions on pathnames. To read or write 15files see :func:`open`, and for accessing the filesystem see the :mod:`os` 16module. The path parameters can be passed as strings, or bytes, or any object 17implementing the :class:`os.PathLike` protocol. 18 19Unlike a Unix shell, Python does not do any *automatic* path expansions. 20Functions such as :func:`expanduser` and :func:`expandvars` can be invoked 21explicitly when an application desires shell-like path expansion. (See also 22the :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 the function :func:`normpath` as 61 follows: ``normpath(join(os.getcwd(), path))``. 62 63 .. versionchanged:: 3.6 64 Accepts a :term:`path-like object`. 65 66 67.. function:: basename(path) 68 69 Return the base name of pathname *path*. This is the second element of the 70 pair returned by passing *path* to the function :func:`split`. Note that 71 the result of this function is different 72 from the Unix :program:`basename` program; where :program:`basename` for 73 ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an 74 empty string (``''``). 75 76 .. versionchanged:: 3.6 77 Accepts a :term:`path-like object`. 78 79 80.. function:: commonpath(paths) 81 82 Return the longest common sub-path of each pathname in the sequence 83 *paths*. Raise :exc:`ValueError` if *paths* contain both absolute 84 and relative pathnames, the *paths* are on the different drives or 85 if *paths* is empty. Unlike :func:`commonprefix`, this returns a 86 valid path. 87 88 .. availability:: Unix, Windows. 89 90 .. versionadded:: 3.5 91 92 .. versionchanged:: 3.6 93 Accepts a sequence of :term:`path-like objects <path-like object>`. 94 95 96.. function:: commonprefix(list) 97 98 Return the longest path prefix (taken character-by-character) that is a 99 prefix of all paths in *list*. If *list* is empty, return the empty string 100 (``''``). 101 102 .. note:: 103 104 This function may return invalid paths because it works a 105 character at a time. To obtain a valid path, see 106 :func:`commonpath`. 107 108 :: 109 110 >>> os.path.commonprefix(['/usr/lib', '/usr/local/lib']) 111 '/usr/l' 112 113 >>> os.path.commonpath(['/usr/lib', '/usr/local/lib']) 114 '/usr' 115 116 .. versionchanged:: 3.6 117 Accepts a :term:`path-like object`. 118 119 120.. function:: dirname(path) 121 122 Return the directory name of pathname *path*. This is the first element of 123 the pair returned by passing *path* to the function :func:`split`. 124 125 .. versionchanged:: 3.6 126 Accepts a :term:`path-like object`. 127 128 129.. function:: exists(path) 130 131 Return ``True`` if *path* refers to an existing path or an open 132 file descriptor. Returns ``False`` for broken symbolic links. On 133 some platforms, this function may return ``False`` if permission is 134 not granted to execute :func:`os.stat` on the requested file, even 135 if the *path* physically exists. 136 137 .. versionchanged:: 3.3 138 *path* can now be an integer: ``True`` is returned if it is an 139 open file descriptor, ``False`` otherwise. 140 141 .. versionchanged:: 3.6 142 Accepts a :term:`path-like object`. 143 144 145.. function:: lexists(path) 146 147 Return ``True`` if *path* refers to an existing path. Returns ``True`` for 148 broken symbolic links. Equivalent to :func:`exists` on platforms lacking 149 :func:`os.lstat`. 150 151 .. versionchanged:: 3.6 152 Accepts a :term:`path-like object`. 153 154 155.. index:: single: ~ (tilde); home directory expansion 156 157.. function:: expanduser(path) 158 159 On Unix and Windows, return the argument with an initial component of ``~`` or 160 ``~user`` replaced by that *user*'s home directory. 161 162 .. index:: pair: module; pwd 163 164 On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME` 165 if it is set; otherwise the current user's home directory is looked up in the 166 password directory through the built-in module :mod:`pwd`. An initial ``~user`` 167 is looked up directly in the password directory. 168 169 On Windows, :envvar:`USERPROFILE` will be used if set, otherwise a combination 170 of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be used. An initial 171 ``~user`` is handled by checking that the last directory component of the current 172 user's home directory matches :envvar:`USERNAME`, and replacing it if so. 173 174 If the expansion fails or if the path does not begin with a tilde, the path is 175 returned unchanged. 176 177 .. versionchanged:: 3.6 178 Accepts a :term:`path-like object`. 179 180 .. versionchanged:: 3.8 181 No longer uses :envvar:`HOME` on Windows. 182 183.. index:: 184 single: $ (dollar); environment variables expansion 185 single: % (percent); environment variables expansion (Windows) 186 187.. function:: expandvars(path) 188 189 Return the argument with environment variables expanded. Substrings of the form 190 ``$name`` or ``${name}`` are replaced by the value of environment variable 191 *name*. Malformed variable names and references to non-existing variables are 192 left unchanged. 193 194 On Windows, ``%name%`` expansions are supported in addition to ``$name`` and 195 ``${name}``. 196 197 .. versionchanged:: 3.6 198 Accepts a :term:`path-like object`. 199 200 201.. function:: getatime(path) 202 203 Return the time of last access of *path*. The return value is a floating point number giving 204 the number of seconds since the epoch (see the :mod:`time` module). Raise 205 :exc:`OSError` if the file does not exist or is inaccessible. 206 207 208.. function:: getmtime(path) 209 210 Return the time of last modification of *path*. The return value is a floating point number 211 giving the number of seconds since the epoch (see the :mod:`time` module). 212 Raise :exc:`OSError` if the file does not exist or is inaccessible. 213 214 .. versionchanged:: 3.6 215 Accepts a :term:`path-like object`. 216 217 218.. function:: getctime(path) 219 220 Return the system's ctime which, on some systems (like Unix) is the time of the 221 last metadata change, and, on others (like Windows), is the creation time for *path*. 222 The return value is a number giving the number of seconds since the epoch (see 223 the :mod:`time` module). Raise :exc:`OSError` if the file does not exist or 224 is inaccessible. 225 226 .. versionchanged:: 3.6 227 Accepts a :term:`path-like object`. 228 229 230.. function:: getsize(path) 231 232 Return the size, in bytes, of *path*. Raise :exc:`OSError` if the file does 233 not exist or is inaccessible. 234 235 .. versionchanged:: 3.6 236 Accepts a :term:`path-like object`. 237 238 239.. function:: isabs(path) 240 241 Return ``True`` if *path* is an absolute pathname. On Unix, that means it 242 begins with a slash, on Windows that it begins with a (back)slash after chopping 243 off a potential drive letter. 244 245 .. versionchanged:: 3.6 246 Accepts a :term:`path-like object`. 247 248 249.. function:: isfile(path) 250 251 Return ``True`` if *path* is an :func:`existing <exists>` regular file. 252 This follows symbolic links, so both :func:`islink` and :func:`isfile` can 253 be true for the same path. 254 255 .. versionchanged:: 3.6 256 Accepts a :term:`path-like object`. 257 258 259.. function:: isdir(path) 260 261 Return ``True`` if *path* is an :func:`existing <exists>` directory. This 262 follows symbolic links, so both :func:`islink` and :func:`isdir` can be true 263 for the same path. 264 265 .. versionchanged:: 3.6 266 Accepts a :term:`path-like object`. 267 268 269.. function:: islink(path) 270 271 Return ``True`` if *path* refers to an :func:`existing <exists>` directory 272 entry that is a symbolic link. Always ``False`` if symbolic links are not 273 supported by the Python runtime. 274 275 .. versionchanged:: 3.6 276 Accepts a :term:`path-like object`. 277 278 279.. function:: ismount(path) 280 281 Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a 282 file system where a different file system has been mounted. On POSIX, the 283 function checks whether *path*'s parent, :file:`{path}/..`, is on a different 284 device than *path*, or whether :file:`{path}/..` and *path* point to the same 285 i-node on the same device --- this should detect mount points for all Unix 286 and POSIX variants. It is not able to reliably detect bind mounts on the 287 same filesystem. On Windows, a drive letter root and a share UNC are 288 always mount points, and for any other path ``GetVolumePathName`` is called 289 to see if it is different from the input path. 290 291 .. versionadded:: 3.4 292 Support for detecting non-root mount points on Windows. 293 294 .. versionchanged:: 3.6 295 Accepts a :term:`path-like object`. 296 297 298.. function:: join(path, *paths) 299 300 Join one or more path segments intelligently. The return value is the 301 concatenation of *path* and all members of *\*paths*, with exactly one 302 directory separator following each non-empty part, except the last. That is, 303 the result will only end in a separator if the last part is either empty or 304 ends in a separator. If a segment is an absolute path (which on Windows 305 requires both a drive and a root), then all previous segments are ignored and 306 joining continues from the absolute path segment. 307 308 On Windows, the drive is not reset when a rooted path segment (e.g., 309 ``r'\foo'``) is encountered. If a segment is on a different drive or is an 310 absolute path, all previous segments are ignored and the drive is reset. Note 311 that since there is a current directory for each drive, 312 ``os.path.join("c:", "foo")`` represents a path relative to the current 313 directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`. 314 315 .. versionchanged:: 3.6 316 Accepts a :term:`path-like object` for *path* and *paths*. 317 318 319.. function:: normcase(path) 320 321 Normalize the case of a pathname. On Windows, convert all characters in the 322 pathname to lowercase, and also convert forward slashes to backward slashes. 323 On other operating systems, return the path unchanged. 324 325 .. versionchanged:: 3.6 326 Accepts a :term:`path-like object`. 327 328 329.. function:: normpath(path) 330 331 Normalize a pathname by collapsing redundant separators and up-level 332 references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all 333 become ``A/B``. This string manipulation may change the meaning of a path 334 that contains symbolic links. On Windows, it converts forward slashes to 335 backward slashes. To normalize case, use :func:`normcase`. 336 337 .. note:: 338 On POSIX systems, in accordance with `IEEE Std 1003.1 2013 Edition; 4.13 339 Pathname Resolution <https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>`_, 340 if a pathname begins with exactly two slashes, the first component 341 following the leading characters may be interpreted in an implementation-defined 342 manner, although more than two leading characters shall be treated as a 343 single character. 344 345 .. versionchanged:: 3.6 346 Accepts a :term:`path-like object`. 347 348 349.. function:: realpath(path, *, strict=False) 350 351 Return the canonical path of the specified filename, eliminating any symbolic 352 links encountered in the path (if they are supported by the operating 353 system). 354 355 By default, the path is evaluated up to the first component that does not 356 exist, is a symlink loop, or whose evaluation raises :exc:`OSError`. 357 All such components are appended unchanged to the existing part of the path. 358 359 Some errors that are handled this way include "access denied", "not a 360 directory", or "bad argument to internal function". Thus, the 361 resulting path may be missing or inaccessible, may still contain 362 links or loops, and may traverse non-directories. 363 364 This behavior can be modified by keyword arguments: 365 366 If *strict* is ``True``, the first error encountered when evaluating the path is 367 re-raised. 368 In particular, :exc:`FileNotFoundError` is raised if *path* does not exist, 369 or another :exc:`OSError` if it is otherwise inaccessible. 370 371 If *strict* is :py:data:`os.path.ALLOW_MISSING`, errors other than 372 :exc:`FileNotFoundError` are re-raised (as with ``strict=True``). 373 Thus, the returned path will not contain any symbolic links, but the named 374 file and some of its parent directories may be missing. 375 376 .. note:: 377 This function emulates the operating system's procedure for making a path 378 canonical, which differs slightly between Windows and UNIX with respect 379 to how links and subsequent path components interact. 380 381 Operating system APIs make paths canonical as needed, so it's not 382 normally necessary to call this function. 383 384 .. versionchanged:: 3.6 385 Accepts a :term:`path-like object`. 386 387 .. versionchanged:: 3.8 388 Symbolic links and junctions are now resolved on Windows. 389 390 .. versionchanged:: 3.10 391 The *strict* parameter was added. 392 393 .. versionchanged:: next 394 The :py:data:`~os.path.ALLOW_MISSING` value for the *strict* parameter 395 was added. 396 397.. data:: ALLOW_MISSING 398 399 Special value used for the *strict* argument in :func:`realpath`. 400 401 .. versionadded:: next 402 403.. function:: relpath(path, start=os.curdir) 404 405 Return a relative filepath to *path* either from the current directory or 406 from an optional *start* directory. This is a path computation: the 407 filesystem is not accessed to confirm the existence or nature of *path* or 408 *start*. On Windows, :exc:`ValueError` is raised when *path* and *start* 409 are on different drives. 410 411 *start* defaults to :attr:`os.curdir`. 412 413 .. availability:: Unix, Windows. 414 415 .. versionchanged:: 3.6 416 Accepts a :term:`path-like object`. 417 418 419.. function:: samefile(path1, path2) 420 421 Return ``True`` if both pathname arguments refer to the same file or directory. 422 This is determined by the device number and i-node number and raises an 423 exception if an :func:`os.stat` call on either pathname fails. 424 425 .. availability:: Unix, Windows. 426 427 .. versionchanged:: 3.2 428 Added Windows support. 429 430 .. versionchanged:: 3.4 431 Windows now uses the same implementation as all other platforms. 432 433 .. versionchanged:: 3.6 434 Accepts a :term:`path-like object`. 435 436 437.. function:: sameopenfile(fp1, fp2) 438 439 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file. 440 441 .. availability:: Unix, Windows. 442 443 .. versionchanged:: 3.2 444 Added Windows support. 445 446 .. versionchanged:: 3.6 447 Accepts a :term:`path-like object`. 448 449 450.. function:: samestat(stat1, stat2) 451 452 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file. 453 These structures may have been returned by :func:`os.fstat`, 454 :func:`os.lstat`, or :func:`os.stat`. This function implements the 455 underlying comparison used by :func:`samefile` and :func:`sameopenfile`. 456 457 .. availability:: Unix, Windows. 458 459 .. versionchanged:: 3.4 460 Added Windows support. 461 462 .. versionchanged:: 3.6 463 Accepts a :term:`path-like object`. 464 465 466.. function:: split(path) 467 468 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the 469 last pathname component and *head* is everything leading up to that. The 470 *tail* part will never contain a slash; if *path* ends in a slash, *tail* 471 will be empty. If there is no slash in *path*, *head* will be empty. If 472 *path* is empty, both *head* and *tail* are empty. Trailing slashes are 473 stripped from *head* unless it is the root (one or more slashes only). In 474 all cases, ``join(head, tail)`` returns a path to the same location as *path* 475 (but the strings may differ). Also see the functions :func:`dirname` and 476 :func:`basename`. 477 478 .. versionchanged:: 3.6 479 Accepts a :term:`path-like object`. 480 481 482.. function:: splitdrive(path) 483 484 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either 485 a mount point or the empty string. On systems which do not use drive 486 specifications, *drive* will always be the empty string. In all cases, ``drive 487 + tail`` will be the same as *path*. 488 489 On Windows, splits a pathname into drive/UNC sharepoint and relative path. 490 491 If the path contains a drive letter, drive will contain everything 492 up to and including the colon:: 493 494 >>> splitdrive("c:/dir") 495 ("c:", "/dir") 496 497 If the path contains a UNC path, drive will contain the host name 498 and share, up to but not including the fourth separator:: 499 500 >>> splitdrive("//host/computer/dir") 501 ("//host/computer", "/dir") 502 503 .. versionchanged:: 3.6 504 Accepts a :term:`path-like object`. 505 506 507.. function:: splitext(path) 508 509 Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext == 510 path``, and the extension, *ext*, is empty or begins with a period and contains at 511 most one period. 512 513 If the path contains no extension, *ext* will be ``''``:: 514 515 >>> splitext('bar') 516 ('bar', '') 517 518 If the path contains an extension, then *ext* will be set to this extension, 519 including the leading period. Note that previous periods will be ignored:: 520 521 >>> splitext('foo.bar.exe') 522 ('foo.bar', '.exe') 523 >>> splitext('/foo/bar.exe') 524 ('/foo/bar', '.exe') 525 526 Leading periods of the last component of the path are considered to 527 be part of the root:: 528 529 >>> splitext('.cshrc') 530 ('.cshrc', '') 531 >>> splitext('/foo/....jpg') 532 ('/foo/....jpg', '') 533 534 .. versionchanged:: 3.6 535 Accepts a :term:`path-like object`. 536 537 538.. data:: supports_unicode_filenames 539 540 ``True`` if arbitrary Unicode strings can be used as file names (within limitations 541 imposed by the file system). 542