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 If a path doesn't exist or a symlink loop is encountered, and *strict* is 356 ``True``, :exc:`OSError` is raised. If *strict* is ``False``, the path is 357 resolved as far as possible and any remainder is appended without checking 358 whether it exists. 359 360 .. note:: 361 This function emulates the operating system's procedure for making a path 362 canonical, which differs slightly between Windows and UNIX with respect 363 to how links and subsequent path components interact. 364 365 Operating system APIs make paths canonical as needed, so it's not 366 normally necessary to call this function. 367 368 .. versionchanged:: 3.6 369 Accepts a :term:`path-like object`. 370 371 .. versionchanged:: 3.8 372 Symbolic links and junctions are now resolved on Windows. 373 374 .. versionchanged:: 3.10 375 The *strict* parameter was added. 376 377 378.. function:: relpath(path, start=os.curdir) 379 380 Return a relative filepath to *path* either from the current directory or 381 from an optional *start* directory. This is a path computation: the 382 filesystem is not accessed to confirm the existence or nature of *path* or 383 *start*. On Windows, :exc:`ValueError` is raised when *path* and *start* 384 are on different drives. 385 386 *start* defaults to :attr:`os.curdir`. 387 388 .. availability:: Unix, Windows. 389 390 .. versionchanged:: 3.6 391 Accepts a :term:`path-like object`. 392 393 394.. function:: samefile(path1, path2) 395 396 Return ``True`` if both pathname arguments refer to the same file or directory. 397 This is determined by the device number and i-node number and raises an 398 exception if an :func:`os.stat` call on either pathname fails. 399 400 .. availability:: Unix, Windows. 401 402 .. versionchanged:: 3.2 403 Added Windows support. 404 405 .. versionchanged:: 3.4 406 Windows now uses the same implementation as all other platforms. 407 408 .. versionchanged:: 3.6 409 Accepts a :term:`path-like object`. 410 411 412.. function:: sameopenfile(fp1, fp2) 413 414 Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file. 415 416 .. availability:: Unix, Windows. 417 418 .. versionchanged:: 3.2 419 Added Windows support. 420 421 .. versionchanged:: 3.6 422 Accepts a :term:`path-like object`. 423 424 425.. function:: samestat(stat1, stat2) 426 427 Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file. 428 These structures may have been returned by :func:`os.fstat`, 429 :func:`os.lstat`, or :func:`os.stat`. This function implements the 430 underlying comparison used by :func:`samefile` and :func:`sameopenfile`. 431 432 .. availability:: Unix, Windows. 433 434 .. versionchanged:: 3.4 435 Added Windows support. 436 437 .. versionchanged:: 3.6 438 Accepts a :term:`path-like object`. 439 440 441.. function:: split(path) 442 443 Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the 444 last pathname component and *head* is everything leading up to that. The 445 *tail* part will never contain a slash; if *path* ends in a slash, *tail* 446 will be empty. If there is no slash in *path*, *head* will be empty. If 447 *path* is empty, both *head* and *tail* are empty. Trailing slashes are 448 stripped from *head* unless it is the root (one or more slashes only). In 449 all cases, ``join(head, tail)`` returns a path to the same location as *path* 450 (but the strings may differ). Also see the functions :func:`dirname` and 451 :func:`basename`. 452 453 .. versionchanged:: 3.6 454 Accepts a :term:`path-like object`. 455 456 457.. function:: splitdrive(path) 458 459 Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either 460 a mount point or the empty string. On systems which do not use drive 461 specifications, *drive* will always be the empty string. In all cases, ``drive 462 + tail`` will be the same as *path*. 463 464 On Windows, splits a pathname into drive/UNC sharepoint and relative path. 465 466 If the path contains a drive letter, drive will contain everything 467 up to and including the colon:: 468 469 >>> splitdrive("c:/dir") 470 ("c:", "/dir") 471 472 If the path contains a UNC path, drive will contain the host name 473 and share, up to but not including the fourth separator:: 474 475 >>> splitdrive("//host/computer/dir") 476 ("//host/computer", "/dir") 477 478 .. versionchanged:: 3.6 479 Accepts a :term:`path-like object`. 480 481 482.. function:: splitext(path) 483 484 Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext == 485 path``, and the extension, *ext*, is empty or begins with a period and contains at 486 most one period. 487 488 If the path contains no extension, *ext* will be ``''``:: 489 490 >>> splitext('bar') 491 ('bar', '') 492 493 If the path contains an extension, then *ext* will be set to this extension, 494 including the leading period. Note that previous periods will be ignored:: 495 496 >>> splitext('foo.bar.exe') 497 ('foo.bar', '.exe') 498 >>> splitext('/foo/bar.exe') 499 ('/foo/bar', '.exe') 500 501 Leading periods of the last component of the path are considered to 502 be part of the root:: 503 504 >>> splitext('.cshrc') 505 ('.cshrc', '') 506 >>> splitext('/foo/....jpg') 507 ('/foo/....jpg', '') 508 509 .. versionchanged:: 3.6 510 Accepts a :term:`path-like object`. 511 512 513.. data:: supports_unicode_filenames 514 515 ``True`` if arbitrary Unicode strings can be used as file names (within limitations 516 imposed by the file system). 517