| 1 |
:mod:`!pathlib` --- Object-oriented filesystem paths |
| 2 |
==================================================== |
| 3 |
|
| 4 |
.. module:: pathlib |
| 5 |
:synopsis: Object-oriented filesystem paths |
| 6 |
|
| 7 |
.. versionadded:: 3.4 |
| 8 |
|
| 9 |
**Source code:** :source:`Lib/pathlib/` |
| 10 |
|
| 11 |
.. index:: single: path; operations |
| 12 |
|
| 13 |
-------------- |
| 14 |
|
| 15 |
This module offers classes representing filesystem paths with semantics |
| 16 |
appropriate for different operating systems. Path classes are divided |
| 17 |
between :ref:`pure paths <pure-paths>`, which provide purely computational |
| 18 |
operations without I/O, and :ref:`concrete paths <concrete-paths>`, which |
| 19 |
inherit from pure paths but also provide I/O operations. |
| 20 |
|
| 21 |
.. image:: pathlib-inheritance.png |
| 22 |
:align: center |
| 23 |
:class: invert-in-dark-mode |
| 24 |
:alt: Inheritance diagram showing the classes available in pathlib. The |
| 25 |
most basic class is PurePath, which has three direct subclasses: |
| 26 |
PurePosixPath, PureWindowsPath, and Path. Further to these four |
| 27 |
classes, there are two classes that use multiple inheritance: |
| 28 |
PosixPath subclasses PurePosixPath and Path, and WindowsPath |
| 29 |
subclasses PureWindowsPath and Path. |
| 30 |
|
| 31 |
If you've never used this module before or just aren't sure which class is |
| 32 |
right for your task, :class:`Path` is most likely what you need. It instantiates |
| 33 |
a :ref:`concrete path <concrete-paths>` for the platform the code is running on. |
| 34 |
|
| 35 |
Pure paths are useful in some special cases; for example: |
| 36 |
|
| 37 |
#. If you want to manipulate Windows paths on a Unix machine (or vice versa). |
| 38 |
You cannot instantiate a :class:`WindowsPath` when running on Unix, but you |
| 39 |
can instantiate :class:`PureWindowsPath`. |
| 40 |
#. You want to make sure that your code only manipulates paths without actually |
| 41 |
accessing the OS. In this case, instantiating one of the pure classes may be |
| 42 |
useful since those simply don't have any OS-accessing operations. |
| 43 |
|
| 44 |
.. seealso:: |
| 45 |
:pep:`428`: The pathlib module -- object-oriented filesystem paths. |
| 46 |
|
| 47 |
.. seealso:: |
| 48 |
For low-level path manipulation on strings, you can also use the |
| 49 |
:mod:`os.path` module. |
| 50 |
|
| 51 |
|
| 52 |
Basic use |
| 53 |
--------- |
| 54 |
|
| 55 |
Importing the main class:: |
| 56 |
|
| 57 |
>>> from pathlib import Path |
| 58 |
|
| 59 |
Listing subdirectories:: |
| 60 |
|
| 61 |
>>> p = Path('.') |
| 62 |
>>> [x for x in p.iterdir() if x.is_dir()] |
| 63 |
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'), |
| 64 |
PosixPath('__pycache__'), PosixPath('build')] |
| 65 |
|
| 66 |
Listing Python source files in this directory tree:: |
| 67 |
|
| 68 |
>>> list(p.glob('**/*.py')) |
| 69 |
[PosixPath('test_pathlib.py'), PosixPath('setup.py'), |
| 70 |
PosixPath('pathlib.py'), PosixPath('docs/conf.py'), |
| 71 |
PosixPath('build/lib/pathlib.py')] |
| 72 |
|
| 73 |
Navigating inside a directory tree:: |
| 74 |
|
| 75 |
>>> p = Path('/etc') |
| 76 |
>>> q = p / 'init.d' / 'reboot' |
| 77 |
>>> q |
| 78 |
PosixPath('/etc/init.d/reboot') |
| 79 |
>>> q.resolve() |
| 80 |
PosixPath('/etc/rc.d/init.d/halt') |
| 81 |
|
| 82 |
Querying path properties:: |
| 83 |
|
| 84 |
>>> q.exists() |
| 85 |
True |
| 86 |
>>> q.is_dir() |
| 87 |
False |
| 88 |
|
| 89 |
Opening a file:: |
| 90 |
|
| 91 |
>>> with q.open() as f: f.readline() |
| 92 |
... |
| 93 |
'#!/bin/bash\n' |
| 94 |
|
| 95 |
|
| 96 |
Exceptions |
| 97 |
---------- |
| 98 |
|
| 99 |
.. exception:: UnsupportedOperation |
| 100 |
|
| 101 |
An exception inheriting :exc:`NotImplementedError` that is raised when an |
| 102 |
unsupported operation is called on a path object. |
| 103 |
|
| 104 |
.. versionadded:: 3.13 |
| 105 |
|
| 106 |
|
| 107 |
.. _pure-paths: |
| 108 |
|
| 109 |
Pure paths |
| 110 |
---------- |
| 111 |
|
| 112 |
Pure path objects provide path-handling operations which don't actually |
| 113 |
access a filesystem. There are three ways to access these classes, which |
| 114 |
we also call *flavours*: |
| 115 |
|
| 116 |
.. class:: PurePath(*pathsegments) |
| 117 |
|
| 118 |
A generic class that represents the system's path flavour (instantiating |
| 119 |
it creates either a :class:`PurePosixPath` or a :class:`PureWindowsPath`):: |
| 120 |
|
| 121 |
>>> PurePath('setup.py') # Running on a Unix machine |
| 122 |
PurePosixPath('setup.py') |
| 123 |
|
| 124 |
Each element of *pathsegments* can be either a string representing a |
| 125 |
path segment, or an object implementing the :class:`os.PathLike` interface |
| 126 |
where the :meth:`~os.PathLike.__fspath__` method returns a string, |
| 127 |
such as another path object:: |
| 128 |
|
| 129 |
>>> PurePath('foo', 'some/path', 'bar') |
| 130 |
PurePosixPath('foo/some/path/bar') |
| 131 |
>>> PurePath(Path('foo'), Path('bar')) |
| 132 |
PurePosixPath('foo/bar') |
| 133 |
|
| 134 |
When *pathsegments* is empty, the current directory is assumed:: |
| 135 |
|
| 136 |
>>> PurePath() |
| 137 |
PurePosixPath('.') |
| 138 |
|
| 139 |
If a segment is an absolute path, all previous segments are ignored |
| 140 |
(like :func:`os.path.join`):: |
| 141 |
|
| 142 |
>>> PurePath('/etc', '/usr', 'lib64') |
| 143 |
PurePosixPath('/usr/lib64') |
| 144 |
>>> PureWindowsPath('c:/Windows', 'd:bar') |
| 145 |
PureWindowsPath('d:bar') |
| 146 |
|
| 147 |
On Windows, the drive is not reset when a rooted relative path |
| 148 |
segment (e.g., ``r'\foo'``) is encountered:: |
| 149 |
|
| 150 |
>>> PureWindowsPath('c:/Windows', '/Program Files') |
| 151 |
PureWindowsPath('c:/Program Files') |
| 152 |
|
| 153 |
Spurious slashes and single dots are collapsed, but double dots (``'..'``) |
| 154 |
and leading double slashes (``'//'``) are not, since this would change the |
| 155 |
meaning of a path for various reasons (e.g. symbolic links, UNC paths):: |
| 156 |
|
| 157 |
>>> PurePath('foo//bar') |
| 158 |
PurePosixPath('foo/bar') |
| 159 |
>>> PurePath('//foo/bar') |
| 160 |
PurePosixPath('//foo/bar') |
| 161 |
>>> PurePath('foo/./bar') |
| 162 |
PurePosixPath('foo/bar') |
| 163 |
>>> PurePath('foo/../bar') |
| 164 |
PurePosixPath('foo/../bar') |
| 165 |
|
| 166 |
(a naïve approach would make ``PurePosixPath('foo/../bar')`` equivalent |
| 167 |
to ``PurePosixPath('bar')``, which is wrong if ``foo`` is a symbolic link |
| 168 |
to another directory) |
| 169 |
|
| 170 |
Pure path objects implement the :class:`os.PathLike` interface, allowing them |
| 171 |
to be used anywhere the interface is accepted. |
| 172 |
|
| 173 |
.. versionchanged:: 3.6 |
| 174 |
Added support for the :class:`os.PathLike` interface. |
| 175 |
|
| 176 |
.. class:: PurePosixPath(*pathsegments) |
| 177 |
|
| 178 |
A subclass of :class:`PurePath`, this path flavour represents non-Windows |
| 179 |
filesystem paths:: |
| 180 |
|
| 181 |
>>> PurePosixPath('/etc/hosts') |
| 182 |
PurePosixPath('/etc/hosts') |
| 183 |
|
| 184 |
*pathsegments* is specified similarly to :class:`PurePath`. |
| 185 |
|
| 186 |
.. class:: PureWindowsPath(*pathsegments) |
| 187 |
|
| 188 |
A subclass of :class:`PurePath`, this path flavour represents Windows |
| 189 |
filesystem paths, including `UNC paths`_:: |
| 190 |
|
| 191 |
>>> PureWindowsPath('c:/', 'Users', 'Ximénez') |
| 192 |
PureWindowsPath('c:/Users/Ximénez') |
| 193 |
>>> PureWindowsPath('//server/share/file') |
| 194 |
PureWindowsPath('//server/share/file') |
| 195 |
|
| 196 |
*pathsegments* is specified similarly to :class:`PurePath`. |
| 197 |
|
| 198 |
.. _unc paths: https://en.wikipedia.org/wiki/Path_(computing)#UNC |
| 199 |
|
| 200 |
Regardless of the system you're running on, you can instantiate all of |
| 201 |
these classes, since they don't provide any operation that does system calls. |
| 202 |
|
| 203 |
|
| 204 |
General properties |
| 205 |
^^^^^^^^^^^^^^^^^^ |
| 206 |
|
| 207 |
Paths are immutable and :term:`hashable`. Paths of a same flavour are comparable |
| 208 |
and orderable. These properties respect the flavour's case-folding |
| 209 |
semantics:: |
| 210 |
|
| 211 |
>>> PurePosixPath('foo') == PurePosixPath('FOO') |
| 212 |
False |
| 213 |
>>> PureWindowsPath('foo') == PureWindowsPath('FOO') |
| 214 |
True |
| 215 |
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') } |
| 216 |
True |
| 217 |
>>> PureWindowsPath('C:') < PureWindowsPath('d:') |
| 218 |
True |
| 219 |
|
| 220 |
Paths of a different flavour compare unequal and cannot be ordered:: |
| 221 |
|
| 222 |
>>> PureWindowsPath('foo') == PurePosixPath('foo') |
| 223 |
False |
| 224 |
>>> PureWindowsPath('foo') < PurePosixPath('foo') |
| 225 |
Traceback (most recent call last): |
| 226 |
File "<stdin>", line 1, in <module> |
| 227 |
TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath' |
| 228 |
|
| 229 |
|
| 230 |
Operators |
| 231 |
^^^^^^^^^ |
| 232 |
|
| 233 |
The slash operator helps create child paths, like :func:`os.path.join`. |
| 234 |
If the argument is an absolute path, the previous path is ignored. |
| 235 |
On Windows, the drive is not reset when the argument is a rooted |
| 236 |
relative path (e.g., ``r'\foo'``):: |
| 237 |
|
| 238 |
>>> p = PurePath('/etc') |
| 239 |
>>> p |
| 240 |
PurePosixPath('/etc') |
| 241 |
>>> p / 'init.d' / 'apache2' |
| 242 |
PurePosixPath('/etc/init.d/apache2') |
| 243 |
>>> q = PurePath('bin') |
| 244 |
>>> '/usr' / q |
| 245 |
PurePosixPath('/usr/bin') |
| 246 |
>>> p / '/an_absolute_path' |
| 247 |
PurePosixPath('/an_absolute_path') |
| 248 |
>>> PureWindowsPath('c:/Windows', '/Program Files') |
| 249 |
PureWindowsPath('c:/Program Files') |
| 250 |
|
| 251 |
A path object can be used anywhere an object implementing :class:`os.PathLike` |
| 252 |
is accepted:: |
| 253 |
|
| 254 |
>>> import os |
| 255 |
>>> p = PurePath('/etc') |
| 256 |
>>> os.fspath(p) |
| 257 |
'/etc' |
| 258 |
|
| 259 |
The string representation of a path is the raw filesystem path itself |
| 260 |
(in native form, e.g. with backslashes under Windows), which you can |
| 261 |
pass to any function taking a file path as a string:: |
| 262 |
|
| 263 |
>>> p = PurePath('/etc') |
| 264 |
>>> str(p) |
| 265 |
'/etc' |
| 266 |
>>> p = PureWindowsPath('c:/Program Files') |
| 267 |
>>> str(p) |
| 268 |
'c:\\Program Files' |
| 269 |
|
| 270 |
Similarly, calling :class:`bytes` on a path gives the raw filesystem path as a |
| 271 |
bytes object, as encoded by :func:`os.fsencode`:: |
| 272 |
|
| 273 |
>>> bytes(p) |
| 274 |
b'/etc' |
| 275 |
|
| 276 |
.. note:: |
| 277 |
Calling :class:`bytes` is only recommended under Unix. Under Windows, |
| 278 |
the unicode form is the canonical representation of filesystem paths. |
| 279 |
|
| 280 |
|
| 281 |
Accessing individual parts |
| 282 |
^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 283 |
|
| 284 |
To access the individual "parts" (components) of a path, use the following |
| 285 |
property: |
| 286 |
|
| 287 |
.. attribute:: PurePath.parts |
| 288 |
|
| 289 |
A tuple giving access to the path's various components:: |
| 290 |
|
| 291 |
>>> p = PurePath('/usr/bin/python3') |
| 292 |
>>> p.parts |
| 293 |
('/', 'usr', 'bin', 'python3') |
| 294 |
|
| 295 |
>>> p = PureWindowsPath('c:/Program Files/PSF') |
| 296 |
>>> p.parts |
| 297 |
('c:\\', 'Program Files', 'PSF') |
| 298 |
|
| 299 |
(note how the drive and local root are regrouped in a single part) |
| 300 |
|
| 301 |
|
| 302 |
Methods and properties |
| 303 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 304 |
|
| 305 |
.. testsetup:: |
| 306 |
|
| 307 |
from pathlib import PurePath, PurePosixPath, PureWindowsPath |
| 308 |
|
| 309 |
Pure paths provide the following methods and properties: |
| 310 |
|
| 311 |
.. attribute:: PurePath.parser |
| 312 |
|
| 313 |
The implementation of the :mod:`os.path` module used for low-level path |
| 314 |
parsing and joining: either :mod:`!posixpath` or :mod:`!ntpath`. |
| 315 |
|
| 316 |
.. versionadded:: 3.13 |
| 317 |
|
| 318 |
.. attribute:: PurePath.drive |
| 319 |
|
| 320 |
A string representing the drive letter or name, if any:: |
| 321 |
|
| 322 |
>>> PureWindowsPath('c:/Program Files/').drive |
| 323 |
'c:' |
| 324 |
>>> PureWindowsPath('/Program Files/').drive |
| 325 |
'' |
| 326 |
>>> PurePosixPath('/etc').drive |
| 327 |
'' |
| 328 |
|
| 329 |
UNC shares are also considered drives:: |
| 330 |
|
| 331 |
>>> PureWindowsPath('//host/share/foo.txt').drive |
| 332 |
'\\\\host\\share' |
| 333 |
|
| 334 |
.. attribute:: PurePath.root |
| 335 |
|
| 336 |
A string representing the (local or global) root, if any:: |
| 337 |
|
| 338 |
>>> PureWindowsPath('c:/Program Files/').root |
| 339 |
'\\' |
| 340 |
>>> PureWindowsPath('c:Program Files/').root |
| 341 |
'' |
| 342 |
>>> PurePosixPath('/etc').root |
| 343 |
'/' |
| 344 |
|
| 345 |
UNC shares always have a root:: |
| 346 |
|
| 347 |
>>> PureWindowsPath('//host/share').root |
| 348 |
'\\' |
| 349 |
|
| 350 |
If the path starts with more than two successive slashes, |
| 351 |
:class:`~pathlib.PurePosixPath` collapses them:: |
| 352 |
|
| 353 |
>>> PurePosixPath('//etc').root |
| 354 |
'//' |
| 355 |
>>> PurePosixPath('///etc').root |
| 356 |
'/' |
| 357 |
>>> PurePosixPath('////etc').root |
| 358 |
'/' |
| 359 |
|
| 360 |
.. note:: |
| 361 |
|
| 362 |
This behavior conforms to *The Open Group Base Specifications Issue 6*, |
| 363 |
paragraph `4.11 Pathname Resolution |
| 364 |
<https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11>`_: |
| 365 |
|
| 366 |
*"A pathname that begins with two successive slashes may be interpreted in |
| 367 |
an implementation-defined manner, although more than two leading slashes |
| 368 |
shall be treated as a single slash."* |
| 369 |
|
| 370 |
.. attribute:: PurePath.anchor |
| 371 |
|
| 372 |
The concatenation of the drive and root:: |
| 373 |
|
| 374 |
>>> PureWindowsPath('c:/Program Files/').anchor |
| 375 |
'c:\\' |
| 376 |
>>> PureWindowsPath('c:Program Files/').anchor |
| 377 |
'c:' |
| 378 |
>>> PurePosixPath('/etc').anchor |
| 379 |
'/' |
| 380 |
>>> PureWindowsPath('//host/share').anchor |
| 381 |
'\\\\host\\share\\' |
| 382 |
|
| 383 |
|
| 384 |
.. attribute:: PurePath.parents |
| 385 |
|
| 386 |
An immutable sequence providing access to the logical ancestors of |
| 387 |
the path:: |
| 388 |
|
| 389 |
>>> p = PureWindowsPath('c:/foo/bar/setup.py') |
| 390 |
>>> p.parents[0] |
| 391 |
PureWindowsPath('c:/foo/bar') |
| 392 |
>>> p.parents[1] |
| 393 |
PureWindowsPath('c:/foo') |
| 394 |
>>> p.parents[2] |
| 395 |
PureWindowsPath('c:/') |
| 396 |
|
| 397 |
.. versionchanged:: 3.10 |
| 398 |
The parents sequence now supports :term:`slices <slice>` and negative index values. |
| 399 |
|
| 400 |
.. attribute:: PurePath.parent |
| 401 |
|
| 402 |
The logical parent of the path:: |
| 403 |
|
| 404 |
>>> p = PurePosixPath('/a/b/c/d') |
| 405 |
>>> p.parent |
| 406 |
PurePosixPath('/a/b/c') |
| 407 |
|
| 408 |
You cannot go past an anchor, or empty path:: |
| 409 |
|
| 410 |
>>> p = PurePosixPath('/') |
| 411 |
>>> p.parent |
| 412 |
PurePosixPath('/') |
| 413 |
>>> p = PurePosixPath('.') |
| 414 |
>>> p.parent |
| 415 |
PurePosixPath('.') |
| 416 |
|
| 417 |
.. note:: |
| 418 |
This is a purely lexical operation, hence the following behaviour:: |
| 419 |
|
| 420 |
>>> p = PurePosixPath('foo/..') |
| 421 |
>>> p.parent |
| 422 |
PurePosixPath('foo') |
| 423 |
|
| 424 |
If you want to walk an arbitrary filesystem path upwards, it is |
| 425 |
recommended to first call :meth:`Path.resolve` so as to resolve |
| 426 |
symlinks and eliminate ``".."`` components. |
| 427 |
|
| 428 |
|
| 429 |
.. attribute:: PurePath.name |
| 430 |
|
| 431 |
A string representing the final path component, excluding the drive and |
| 432 |
root, if any:: |
| 433 |
|
| 434 |
>>> PurePosixPath('my/library/setup.py').name |
| 435 |
'setup.py' |
| 436 |
|
| 437 |
UNC drive names are not considered:: |
| 438 |
|
| 439 |
>>> PureWindowsPath('//some/share/setup.py').name |
| 440 |
'setup.py' |
| 441 |
>>> PureWindowsPath('//some/share').name |
| 442 |
'' |
| 443 |
|
| 444 |
|
| 445 |
.. attribute:: PurePath.suffix |
| 446 |
|
| 447 |
The last dot-separated portion of the final component, if any:: |
| 448 |
|
| 449 |
>>> PurePosixPath('my/library/setup.py').suffix |
| 450 |
'.py' |
| 451 |
>>> PurePosixPath('my/library.tar.gz').suffix |
| 452 |
'.gz' |
| 453 |
>>> PurePosixPath('my/library').suffix |
| 454 |
'' |
| 455 |
|
| 456 |
This is commonly called the file extension. |
| 457 |
|
| 458 |
.. versionchanged:: 3.14 |
| 459 |
|
| 460 |
A single dot ("``.``") is considered a valid suffix. |
| 461 |
|
| 462 |
.. attribute:: PurePath.suffixes |
| 463 |
|
| 464 |
A list of the path's suffixes, often called file extensions:: |
| 465 |
|
| 466 |
>>> PurePosixPath('my/library.tar.gar').suffixes |
| 467 |
['.tar', '.gar'] |
| 468 |
>>> PurePosixPath('my/library.tar.gz').suffixes |
| 469 |
['.tar', '.gz'] |
| 470 |
>>> PurePosixPath('my/library').suffixes |
| 471 |
[] |
| 472 |
|
| 473 |
.. versionchanged:: 3.14 |
| 474 |
|
| 475 |
A single dot ("``.``") is considered a valid suffix. |
| 476 |
|
| 477 |
|
| 478 |
.. attribute:: PurePath.stem |
| 479 |
|
| 480 |
The final path component, without its suffix:: |
| 481 |
|
| 482 |
>>> PurePosixPath('my/library.tar.gz').stem |
| 483 |
'library.tar' |
| 484 |
>>> PurePosixPath('my/library.tar').stem |
| 485 |
'library' |
| 486 |
>>> PurePosixPath('my/library').stem |
| 487 |
'library' |
| 488 |
|
| 489 |
.. versionchanged:: 3.14 |
| 490 |
|
| 491 |
A single dot ("``.``") is considered a valid suffix. |
| 492 |
|
| 493 |
|
| 494 |
.. method:: PurePath.as_posix() |
| 495 |
|
| 496 |
Return a string representation of the path with forward slashes (``/``):: |
| 497 |
|
| 498 |
>>> p = PureWindowsPath('c:\\windows') |
| 499 |
>>> str(p) |
| 500 |
'c:\\windows' |
| 501 |
>>> p.as_posix() |
| 502 |
'c:/windows' |
| 503 |
|
| 504 |
|
| 505 |
.. method:: PurePath.is_absolute() |
| 506 |
|
| 507 |
Return whether the path is absolute or not. A path is considered absolute |
| 508 |
if it has both a root and (if the flavour allows) a drive:: |
| 509 |
|
| 510 |
>>> PurePosixPath('/a/b').is_absolute() |
| 511 |
True |
| 512 |
>>> PurePosixPath('a/b').is_absolute() |
| 513 |
False |
| 514 |
|
| 515 |
>>> PureWindowsPath('c:/a/b').is_absolute() |
| 516 |
True |
| 517 |
>>> PureWindowsPath('/a/b').is_absolute() |
| 518 |
False |
| 519 |
>>> PureWindowsPath('c:').is_absolute() |
| 520 |
False |
| 521 |
>>> PureWindowsPath('//some/share').is_absolute() |
| 522 |
True |
| 523 |
|
| 524 |
|
| 525 |
.. method:: PurePath.is_relative_to(other) |
| 526 |
|
| 527 |
Return whether or not this path is relative to the *other* path. |
| 528 |
|
| 529 |
>>> p = PurePath('/etc/passwd') |
| 530 |
>>> p.is_relative_to('/etc') |
| 531 |
True |
| 532 |
>>> p.is_relative_to('/usr') |
| 533 |
False |
| 534 |
|
| 535 |
This method is string-based; it neither accesses the filesystem nor treats |
| 536 |
"``..``" segments specially. The following code is equivalent: |
| 537 |
|
| 538 |
>>> u = PurePath('/usr') |
| 539 |
>>> u == p or u in p.parents |
| 540 |
False |
| 541 |
|
| 542 |
.. versionadded:: 3.9 |
| 543 |
|
| 544 |
.. deprecated-removed:: 3.12 3.14 |
| 545 |
|
| 546 |
Passing additional arguments is deprecated; if supplied, they are joined |
| 547 |
with *other*. |
| 548 |
|
| 549 |
.. method:: PurePath.is_reserved() |
| 550 |
|
| 551 |
With :class:`PureWindowsPath`, return ``True`` if the path is considered |
| 552 |
reserved under Windows, ``False`` otherwise. With :class:`PurePosixPath`, |
| 553 |
``False`` is always returned. |
| 554 |
|
| 555 |
.. versionchanged:: 3.13 |
| 556 |
Windows path names that contain a colon, or end with a dot or a space, |
| 557 |
are considered reserved. UNC paths may be reserved. |
| 558 |
|
| 559 |
.. deprecated-removed:: 3.13 3.15 |
| 560 |
This method is deprecated; use :func:`os.path.isreserved` to detect |
| 561 |
reserved paths on Windows. |
| 562 |
|
| 563 |
.. method:: PurePath.joinpath(*pathsegments) |
| 564 |
|
| 565 |
Calling this method is equivalent to combining the path with each of |
| 566 |
the given *pathsegments* in turn:: |
| 567 |
|
| 568 |
>>> PurePosixPath('/etc').joinpath('passwd') |
| 569 |
PurePosixPath('/etc/passwd') |
| 570 |
>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd')) |
| 571 |
PurePosixPath('/etc/passwd') |
| 572 |
>>> PurePosixPath('/etc').joinpath('init.d', 'apache2') |
| 573 |
PurePosixPath('/etc/init.d/apache2') |
| 574 |
>>> PureWindowsPath('c:').joinpath('/Program Files') |
| 575 |
PureWindowsPath('c:/Program Files') |
| 576 |
|
| 577 |
|
| 578 |
.. method:: PurePath.full_match(pattern, *, case_sensitive=None) |
| 579 |
|
| 580 |
Match this path against the provided glob-style pattern. Return ``True`` |
| 581 |
if matching is successful, ``False`` otherwise. For example:: |
| 582 |
|
| 583 |
>>> PurePath('a/b.py').full_match('a/*.py') |
| 584 |
True |
| 585 |
>>> PurePath('a/b.py').full_match('*.py') |
| 586 |
False |
| 587 |
>>> PurePath('/a/b/c.py').full_match('/a/**') |
| 588 |
True |
| 589 |
>>> PurePath('/a/b/c.py').full_match('**/*.py') |
| 590 |
True |
| 591 |
|
| 592 |
.. seealso:: |
| 593 |
:ref:`pathlib-pattern-language` documentation. |
| 594 |
|
| 595 |
As with other methods, case-sensitivity follows platform defaults:: |
| 596 |
|
| 597 |
>>> PurePosixPath('b.py').full_match('*.PY') |
| 598 |
False |
| 599 |
>>> PureWindowsPath('b.py').full_match('*.PY') |
| 600 |
True |
| 601 |
|
| 602 |
Set *case_sensitive* to ``True`` or ``False`` to override this behaviour. |
| 603 |
|
| 604 |
.. versionadded:: 3.13 |
| 605 |
|
| 606 |
|
| 607 |
.. method:: PurePath.match(pattern, *, case_sensitive=None) |
| 608 |
|
| 609 |
Match this path against the provided non-recursive glob-style pattern. |
| 610 |
Return ``True`` if matching is successful, ``False`` otherwise. |
| 611 |
|
| 612 |
This method is similar to :meth:`~PurePath.full_match`, but empty patterns |
| 613 |
aren't allowed (:exc:`ValueError` is raised), the recursive wildcard |
| 614 |
"``**``" isn't supported (it acts like non-recursive "``*``"), and if a |
| 615 |
relative pattern is provided, then matching is done from the right:: |
| 616 |
|
| 617 |
>>> PurePath('a/b.py').match('*.py') |
| 618 |
True |
| 619 |
>>> PurePath('/a/b/c.py').match('b/*.py') |
| 620 |
True |
| 621 |
>>> PurePath('/a/b/c.py').match('a/*.py') |
| 622 |
False |
| 623 |
|
| 624 |
.. versionchanged:: 3.12 |
| 625 |
The *pattern* parameter accepts a :term:`path-like object`. |
| 626 |
|
| 627 |
.. versionchanged:: 3.12 |
| 628 |
The *case_sensitive* parameter was added. |
| 629 |
|
| 630 |
|
| 631 |
.. method:: PurePath.relative_to(other, walk_up=False) |
| 632 |
|
| 633 |
Compute a version of this path relative to the path represented by |
| 634 |
*other*. If it's impossible, :exc:`ValueError` is raised:: |
| 635 |
|
| 636 |
>>> p = PurePosixPath('/etc/passwd') |
| 637 |
>>> p.relative_to('/') |
| 638 |
PurePosixPath('etc/passwd') |
| 639 |
>>> p.relative_to('/etc') |
| 640 |
PurePosixPath('passwd') |
| 641 |
>>> p.relative_to('/usr') |
| 642 |
Traceback (most recent call last): |
| 643 |
File "<stdin>", line 1, in <module> |
| 644 |
File "pathlib.py", line 941, in relative_to |
| 645 |
raise ValueError(error_message.format(str(self), str(formatted))) |
| 646 |
ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other is absolute. |
| 647 |
|
| 648 |
When *walk_up* is false (the default), the path must start with *other*. |
| 649 |
When the argument is true, ``..`` entries may be added to form the |
| 650 |
relative path. In all other cases, such as the paths referencing |
| 651 |
different drives, :exc:`ValueError` is raised.:: |
| 652 |
|
| 653 |
>>> p.relative_to('/usr', walk_up=True) |
| 654 |
PurePosixPath('../etc/passwd') |
| 655 |
>>> p.relative_to('foo', walk_up=True) |
| 656 |
Traceback (most recent call last): |
| 657 |
File "<stdin>", line 1, in <module> |
| 658 |
File "pathlib.py", line 941, in relative_to |
| 659 |
raise ValueError(error_message.format(str(self), str(formatted))) |
| 660 |
ValueError: '/etc/passwd' is not on the same drive as 'foo' OR one path is relative and the other is absolute. |
| 661 |
|
| 662 |
.. warning:: |
| 663 |
This function is part of :class:`PurePath` and works with strings. |
| 664 |
It does not check or access the underlying file structure. |
| 665 |
This can impact the *walk_up* option as it assumes that no symlinks |
| 666 |
are present in the path; call :meth:`~Path.resolve` first if |
| 667 |
necessary to resolve symlinks. |
| 668 |
|
| 669 |
.. versionchanged:: 3.12 |
| 670 |
The *walk_up* parameter was added (old behavior is the same as ``walk_up=False``). |
| 671 |
|
| 672 |
.. deprecated-removed:: 3.12 3.14 |
| 673 |
|
| 674 |
Passing additional positional arguments is deprecated; if supplied, |
| 675 |
they are joined with *other*. |
| 676 |
|
| 677 |
.. method:: PurePath.with_name(name) |
| 678 |
|
| 679 |
Return a new path with the :attr:`name` changed. If the original path |
| 680 |
doesn't have a name, ValueError is raised:: |
| 681 |
|
| 682 |
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') |
| 683 |
>>> p.with_name('setup.py') |
| 684 |
PureWindowsPath('c:/Downloads/setup.py') |
| 685 |
>>> p = PureWindowsPath('c:/') |
| 686 |
>>> p.with_name('setup.py') |
| 687 |
Traceback (most recent call last): |
| 688 |
File "<stdin>", line 1, in <module> |
| 689 |
File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name |
| 690 |
raise ValueError("%r has an empty name" % (self,)) |
| 691 |
ValueError: PureWindowsPath('c:/') has an empty name |
| 692 |
|
| 693 |
|
| 694 |
.. method:: PurePath.with_stem(stem) |
| 695 |
|
| 696 |
Return a new path with the :attr:`stem` changed. If the original path |
| 697 |
doesn't have a name, ValueError is raised:: |
| 698 |
|
| 699 |
>>> p = PureWindowsPath('c:/Downloads/draft.txt') |
| 700 |
>>> p.with_stem('final') |
| 701 |
PureWindowsPath('c:/Downloads/final.txt') |
| 702 |
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') |
| 703 |
>>> p.with_stem('lib') |
| 704 |
PureWindowsPath('c:/Downloads/lib.gz') |
| 705 |
>>> p = PureWindowsPath('c:/') |
| 706 |
>>> p.with_stem('') |
| 707 |
Traceback (most recent call last): |
| 708 |
File "<stdin>", line 1, in <module> |
| 709 |
File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem |
| 710 |
return self.with_name(stem + self.suffix) |
| 711 |
File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name |
| 712 |
raise ValueError("%r has an empty name" % (self,)) |
| 713 |
ValueError: PureWindowsPath('c:/') has an empty name |
| 714 |
|
| 715 |
.. versionadded:: 3.9 |
| 716 |
|
| 717 |
|
| 718 |
.. method:: PurePath.with_suffix(suffix) |
| 719 |
|
| 720 |
Return a new path with the :attr:`suffix` changed. If the original path |
| 721 |
doesn't have a suffix, the new *suffix* is appended instead. If the |
| 722 |
*suffix* is an empty string, the original suffix is removed:: |
| 723 |
|
| 724 |
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') |
| 725 |
>>> p.with_suffix('.bz2') |
| 726 |
PureWindowsPath('c:/Downloads/pathlib.tar.bz2') |
| 727 |
>>> p = PureWindowsPath('README') |
| 728 |
>>> p.with_suffix('.txt') |
| 729 |
PureWindowsPath('README.txt') |
| 730 |
>>> p = PureWindowsPath('README.txt') |
| 731 |
>>> p.with_suffix('') |
| 732 |
PureWindowsPath('README') |
| 733 |
|
| 734 |
.. versionchanged:: 3.14 |
| 735 |
|
| 736 |
A single dot ("``.``") is considered a valid suffix. In previous |
| 737 |
versions, :exc:`ValueError` is raised if a single dot is supplied. |
| 738 |
|
| 739 |
|
| 740 |
.. method:: PurePath.with_segments(*pathsegments) |
| 741 |
|
| 742 |
Create a new path object of the same type by combining the given |
| 743 |
*pathsegments*. This method is called whenever a derivative path is created, |
| 744 |
such as from :attr:`parent` and :meth:`relative_to`. Subclasses may |
| 745 |
override this method to pass information to derivative paths, for example:: |
| 746 |
|
| 747 |
from pathlib import PurePosixPath |
| 748 |
|
| 749 |
class MyPath(PurePosixPath): |
| 750 |
def __init__(self, *pathsegments, session_id): |
| 751 |
super().__init__(*pathsegments) |
| 752 |
self.session_id = session_id |
| 753 |
|
| 754 |
def with_segments(self, *pathsegments): |
| 755 |
return type(self)(*pathsegments, session_id=self.session_id) |
| 756 |
|
| 757 |
etc = MyPath('/etc', session_id=42) |
| 758 |
hosts = etc / 'hosts' |
| 759 |
print(hosts.session_id) # 42 |
| 760 |
|
| 761 |
.. versionadded:: 3.12 |
| 762 |
|
| 763 |
|
| 764 |
.. _concrete-paths: |
| 765 |
|
| 766 |
|
| 767 |
Concrete paths |
| 768 |
-------------- |
| 769 |
|
| 770 |
Concrete paths are subclasses of the pure path classes. In addition to |
| 771 |
operations provided by the latter, they also provide methods to do system |
| 772 |
calls on path objects. There are three ways to instantiate concrete paths: |
| 773 |
|
| 774 |
.. class:: Path(*pathsegments) |
| 775 |
|
| 776 |
A subclass of :class:`PurePath`, this class represents concrete paths of |
| 777 |
the system's path flavour (instantiating it creates either a |
| 778 |
:class:`PosixPath` or a :class:`WindowsPath`):: |
| 779 |
|
| 780 |
>>> Path('setup.py') |
| 781 |
PosixPath('setup.py') |
| 782 |
|
| 783 |
*pathsegments* is specified similarly to :class:`PurePath`. |
| 784 |
|
| 785 |
.. class:: PosixPath(*pathsegments) |
| 786 |
|
| 787 |
A subclass of :class:`Path` and :class:`PurePosixPath`, this class |
| 788 |
represents concrete non-Windows filesystem paths:: |
| 789 |
|
| 790 |
>>> PosixPath('/etc/hosts') |
| 791 |
PosixPath('/etc/hosts') |
| 792 |
|
| 793 |
*pathsegments* is specified similarly to :class:`PurePath`. |
| 794 |
|
| 795 |
.. versionchanged:: 3.13 |
| 796 |
Raises :exc:`UnsupportedOperation` on Windows. In previous versions, |
| 797 |
:exc:`NotImplementedError` was raised instead. |
| 798 |
|
| 799 |
|
| 800 |
.. class:: WindowsPath(*pathsegments) |
| 801 |
|
| 802 |
A subclass of :class:`Path` and :class:`PureWindowsPath`, this class |
| 803 |
represents concrete Windows filesystem paths:: |
| 804 |
|
| 805 |
>>> WindowsPath('c:/', 'Users', 'Ximénez') |
| 806 |
WindowsPath('c:/Users/Ximénez') |
| 807 |
|
| 808 |
*pathsegments* is specified similarly to :class:`PurePath`. |
| 809 |
|
| 810 |
.. versionchanged:: 3.13 |
| 811 |
Raises :exc:`UnsupportedOperation` on non-Windows platforms. In previous |
| 812 |
versions, :exc:`NotImplementedError` was raised instead. |
| 813 |
|
| 814 |
|
| 815 |
You can only instantiate the class flavour that corresponds to your system |
| 816 |
(allowing system calls on non-compatible path flavours could lead to |
| 817 |
bugs or failures in your application):: |
| 818 |
|
| 819 |
>>> import os |
| 820 |
>>> os.name |
| 821 |
'posix' |
| 822 |
>>> Path('setup.py') |
| 823 |
PosixPath('setup.py') |
| 824 |
>>> PosixPath('setup.py') |
| 825 |
PosixPath('setup.py') |
| 826 |
>>> WindowsPath('setup.py') |
| 827 |
Traceback (most recent call last): |
| 828 |
File "<stdin>", line 1, in <module> |
| 829 |
File "pathlib.py", line 798, in __new__ |
| 830 |
% (cls.__name__,)) |
| 831 |
UnsupportedOperation: cannot instantiate 'WindowsPath' on your system |
| 832 |
|
| 833 |
Some concrete path methods can raise an :exc:`OSError` if a system call fails |
| 834 |
(for example because the path doesn't exist). |
| 835 |
|
| 836 |
|
| 837 |
Parsing and generating URIs |
| 838 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 839 |
|
| 840 |
Concrete path objects can be created from, and represented as, 'file' URIs |
| 841 |
conforming to :rfc:`8089`. |
| 842 |
|
| 843 |
.. note:: |
| 844 |
|
| 845 |
File URIs are not portable across machines with different |
| 846 |
:ref:`filesystem encodings <filesystem-encoding>`. |
| 847 |
|
| 848 |
.. classmethod:: Path.from_uri(uri) |
| 849 |
|
| 850 |
Return a new path object from parsing a 'file' URI. For example:: |
| 851 |
|
| 852 |
>>> p = Path.from_uri('file:///etc/hosts') |
| 853 |
PosixPath('/etc/hosts') |
| 854 |
|
| 855 |
On Windows, DOS device and UNC paths may be parsed from URIs:: |
| 856 |
|
| 857 |
>>> p = Path.from_uri('file:///c:/windows') |
| 858 |
WindowsPath('c:/windows') |
| 859 |
>>> p = Path.from_uri('file://server/share') |
| 860 |
WindowsPath('//server/share') |
| 861 |
|
| 862 |
Several variant forms are supported:: |
| 863 |
|
| 864 |
>>> p = Path.from_uri('file:////server/share') |
| 865 |
WindowsPath('//server/share') |
| 866 |
>>> p = Path.from_uri('file://///server/share') |
| 867 |
WindowsPath('//server/share') |
| 868 |
>>> p = Path.from_uri('file:c:/windows') |
| 869 |
WindowsPath('c:/windows') |
| 870 |
>>> p = Path.from_uri('file:/c|/windows') |
| 871 |
WindowsPath('c:/windows') |
| 872 |
|
| 873 |
:exc:`ValueError` is raised if the URI does not start with ``file:``, or |
| 874 |
the parsed path isn't absolute. |
| 875 |
|
| 876 |
.. versionadded:: 3.13 |
| 877 |
|
| 878 |
.. versionchanged:: 3.14 |
| 879 |
The URL authority is discarded if it matches the local hostname. |
| 880 |
Otherwise, if the authority isn't empty or ``localhost``, then on |
| 881 |
Windows a UNC path is returned (as before), and on other platforms a |
| 882 |
:exc:`ValueError` is raised. |
| 883 |
|
| 884 |
|
| 885 |
.. method:: Path.as_uri() |
| 886 |
|
| 887 |
Represent the path as a 'file' URI. :exc:`ValueError` is raised if |
| 888 |
the path isn't absolute. |
| 889 |
|
| 890 |
.. code-block:: pycon |
| 891 |
|
| 892 |
>>> p = PosixPath('/etc/passwd') |
| 893 |
>>> p.as_uri() |
| 894 |
'file:///etc/passwd' |
| 895 |
>>> p = WindowsPath('c:/Windows') |
| 896 |
>>> p.as_uri() |
| 897 |
'file:///c:/Windows' |
| 898 |
|
| 899 |
.. deprecated-removed:: 3.14 3.19 |
| 900 |
|
| 901 |
Calling this method from :class:`PurePath` rather than :class:`Path` is |
| 902 |
possible but deprecated. The method's use of :func:`os.fsencode` makes |
| 903 |
it strictly impure. |
| 904 |
|
| 905 |
|
| 906 |
Expanding and resolving paths |
| 907 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 908 |
|
| 909 |
.. classmethod:: Path.home() |
| 910 |
|
| 911 |
Return a new path object representing the user's home directory (as |
| 912 |
returned by :func:`os.path.expanduser` with ``~`` construct). If the home |
| 913 |
directory can't be resolved, :exc:`RuntimeError` is raised. |
| 914 |
|
| 915 |
:: |
| 916 |
|
| 917 |
>>> Path.home() |
| 918 |
PosixPath('/home/antoine') |
| 919 |
|
| 920 |
.. versionadded:: 3.5 |
| 921 |
|
| 922 |
|
| 923 |
.. method:: Path.expanduser() |
| 924 |
|
| 925 |
Return a new path with expanded ``~`` and ``~user`` constructs, |
| 926 |
as returned by :meth:`os.path.expanduser`. If a home directory can't be |
| 927 |
resolved, :exc:`RuntimeError` is raised. |
| 928 |
|
| 929 |
:: |
| 930 |
|
| 931 |
>>> p = PosixPath('~/films/Monty Python') |
| 932 |
>>> p.expanduser() |
| 933 |
PosixPath('/home/eric/films/Monty Python') |
| 934 |
|
| 935 |
.. versionadded:: 3.5 |
| 936 |
|
| 937 |
|
| 938 |
.. classmethod:: Path.cwd() |
| 939 |
|
| 940 |
Return a new path object representing the current directory (as returned |
| 941 |
by :func:`os.getcwd`):: |
| 942 |
|
| 943 |
>>> Path.cwd() |
| 944 |
PosixPath('/home/antoine/pathlib') |
| 945 |
|
| 946 |
|
| 947 |
.. method:: Path.absolute() |
| 948 |
|
| 949 |
Make the path absolute, without normalization or resolving symlinks. |
| 950 |
Returns a new path object:: |
| 951 |
|
| 952 |
>>> p = Path('tests') |
| 953 |
>>> p |
| 954 |
PosixPath('tests') |
| 955 |
>>> p.absolute() |
| 956 |
PosixPath('/home/antoine/pathlib/tests') |
| 957 |
|
| 958 |
|
| 959 |
.. method:: Path.resolve(strict=False) |
| 960 |
|
| 961 |
Make the path absolute, resolving any symlinks. A new path object is |
| 962 |
returned:: |
| 963 |
|
| 964 |
>>> p = Path() |
| 965 |
>>> p |
| 966 |
PosixPath('.') |
| 967 |
>>> p.resolve() |
| 968 |
PosixPath('/home/antoine/pathlib') |
| 969 |
|
| 970 |
"``..``" components are also eliminated (this is the only method to do so):: |
| 971 |
|
| 972 |
>>> p = Path('docs/../setup.py') |
| 973 |
>>> p.resolve() |
| 974 |
PosixPath('/home/antoine/pathlib/setup.py') |
| 975 |
|
| 976 |
If a path doesn't exist or a symlink loop is encountered, and *strict* is |
| 977 |
``True``, :exc:`OSError` is raised. If *strict* is ``False``, the path is |
| 978 |
resolved as far as possible and any remainder is appended without checking |
| 979 |
whether it exists. |
| 980 |
|
| 981 |
.. versionchanged:: 3.6 |
| 982 |
The *strict* parameter was added (pre-3.6 behavior is strict). |
| 983 |
|
| 984 |
.. versionchanged:: 3.13 |
| 985 |
Symlink loops are treated like other errors: :exc:`OSError` is raised in |
| 986 |
strict mode, and no exception is raised in non-strict mode. In previous |
| 987 |
versions, :exc:`RuntimeError` is raised no matter the value of *strict*. |
| 988 |
|
| 989 |
|
| 990 |
.. method:: Path.readlink() |
| 991 |
|
| 992 |
Return the path to which the symbolic link points (as returned by |
| 993 |
:func:`os.readlink`):: |
| 994 |
|
| 995 |
>>> p = Path('mylink') |
| 996 |
>>> p.symlink_to('setup.py') |
| 997 |
>>> p.readlink() |
| 998 |
PosixPath('setup.py') |
| 999 |
|
| 1000 |
.. versionadded:: 3.9 |
| 1001 |
|
| 1002 |
.. versionchanged:: 3.13 |
| 1003 |
Raises :exc:`UnsupportedOperation` if :func:`os.readlink` is not |
| 1004 |
available. In previous versions, :exc:`NotImplementedError` was raised. |
| 1005 |
|
| 1006 |
|
| 1007 |
Querying file type and status |
| 1008 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1009 |
|
| 1010 |
.. versionchanged:: 3.8 |
| 1011 |
|
| 1012 |
:meth:`~Path.exists`, :meth:`~Path.is_dir`, :meth:`~Path.is_file`, |
| 1013 |
:meth:`~Path.is_mount`, :meth:`~Path.is_symlink`, |
| 1014 |
:meth:`~Path.is_block_device`, :meth:`~Path.is_char_device`, |
| 1015 |
:meth:`~Path.is_fifo`, :meth:`~Path.is_socket` now return ``False`` |
| 1016 |
instead of raising an exception for paths that contain characters |
| 1017 |
unrepresentable at the OS level. |
| 1018 |
|
| 1019 |
.. versionchanged:: 3.14 |
| 1020 |
|
| 1021 |
The methods given above now return ``False`` instead of raising any |
| 1022 |
:exc:`OSError` exception from the operating system. In previous versions, |
| 1023 |
some kinds of :exc:`OSError` exception are raised, and others suppressed. |
| 1024 |
The new behaviour is consistent with :func:`os.path.exists`, |
| 1025 |
:func:`os.path.isdir`, etc. Use :meth:`~Path.stat` to retrieve the file |
| 1026 |
status without suppressing exceptions. |
| 1027 |
|
| 1028 |
|
| 1029 |
.. method:: Path.stat(*, follow_symlinks=True) |
| 1030 |
|
| 1031 |
Return an :class:`os.stat_result` object containing information about this path, like :func:`os.stat`. |
| 1032 |
The result is looked up at each call to this method. |
| 1033 |
|
| 1034 |
This method normally follows symlinks; to stat a symlink add the argument |
| 1035 |
``follow_symlinks=False``, or use :meth:`~Path.lstat`. |
| 1036 |
|
| 1037 |
:: |
| 1038 |
|
| 1039 |
>>> p = Path('setup.py') |
| 1040 |
>>> p.stat().st_size |
| 1041 |
956 |
| 1042 |
>>> p.stat().st_mtime |
| 1043 |
1327883547.852554 |
| 1044 |
|
| 1045 |
.. versionchanged:: 3.10 |
| 1046 |
The *follow_symlinks* parameter was added. |
| 1047 |
|
| 1048 |
|
| 1049 |
.. method:: Path.lstat() |
| 1050 |
|
| 1051 |
Like :meth:`Path.stat` but, if the path points to a symbolic link, return |
| 1052 |
the symbolic link's information rather than its target's. |
| 1053 |
|
| 1054 |
|
| 1055 |
.. method:: Path.exists(*, follow_symlinks=True) |
| 1056 |
|
| 1057 |
Return ``True`` if the path points to an existing file or directory. |
| 1058 |
``False`` will be returned if the path is invalid, inaccessible or missing. |
| 1059 |
Use :meth:`Path.stat` to distinguish between these cases. |
| 1060 |
|
| 1061 |
This method normally follows symlinks; to check if a symlink exists, add |
| 1062 |
the argument ``follow_symlinks=False``. |
| 1063 |
|
| 1064 |
:: |
| 1065 |
|
| 1066 |
>>> Path('.').exists() |
| 1067 |
True |
| 1068 |
>>> Path('setup.py').exists() |
| 1069 |
True |
| 1070 |
>>> Path('/etc').exists() |
| 1071 |
True |
| 1072 |
>>> Path('nonexistentfile').exists() |
| 1073 |
False |
| 1074 |
|
| 1075 |
.. versionchanged:: 3.12 |
| 1076 |
The *follow_symlinks* parameter was added. |
| 1077 |
|
| 1078 |
|
| 1079 |
.. method:: Path.is_file(*, follow_symlinks=True) |
| 1080 |
|
| 1081 |
Return ``True`` if the path points to a regular file. ``False`` will be |
| 1082 |
returned if the path is invalid, inaccessible or missing, or if it points |
| 1083 |
to something other than a regular file. Use :meth:`Path.stat` to |
| 1084 |
distinguish between these cases. |
| 1085 |
|
| 1086 |
This method normally follows symlinks; to exclude symlinks, add the |
| 1087 |
argument ``follow_symlinks=False``. |
| 1088 |
|
| 1089 |
.. versionchanged:: 3.13 |
| 1090 |
The *follow_symlinks* parameter was added. |
| 1091 |
|
| 1092 |
|
| 1093 |
.. method:: Path.is_dir(*, follow_symlinks=True) |
| 1094 |
|
| 1095 |
Return ``True`` if the path points to a directory. ``False`` will be |
| 1096 |
returned if the path is invalid, inaccessible or missing, or if it points |
| 1097 |
to something other than a directory. Use :meth:`Path.stat` to distinguish |
| 1098 |
between these cases. |
| 1099 |
|
| 1100 |
This method normally follows symlinks; to exclude symlinks to directories, |
| 1101 |
add the argument ``follow_symlinks=False``. |
| 1102 |
|
| 1103 |
.. versionchanged:: 3.13 |
| 1104 |
The *follow_symlinks* parameter was added. |
| 1105 |
|
| 1106 |
|
| 1107 |
.. method:: Path.is_symlink() |
| 1108 |
|
| 1109 |
Return ``True`` if the path points to a symbolic link, even if that symlink |
| 1110 |
is broken. ``False`` will be returned if the path is invalid, inaccessible |
| 1111 |
or missing, or if it points to something other than a symbolic link. Use |
| 1112 |
:meth:`Path.stat` to distinguish between these cases. |
| 1113 |
|
| 1114 |
|
| 1115 |
.. method:: Path.is_junction() |
| 1116 |
|
| 1117 |
Return ``True`` if the path points to a junction, and ``False`` for any other |
| 1118 |
type of file. Currently only Windows supports junctions. |
| 1119 |
|
| 1120 |
.. versionadded:: 3.12 |
| 1121 |
|
| 1122 |
|
| 1123 |
.. method:: Path.is_mount() |
| 1124 |
|
| 1125 |
Return ``True`` if the path is a :dfn:`mount point`: a point in a |
| 1126 |
file system where a different file system has been mounted. On POSIX, the |
| 1127 |
function checks whether *path*'s parent, :file:`path/..`, is on a different |
| 1128 |
device than *path*, or whether :file:`path/..` and *path* point to the same |
| 1129 |
i-node on the same device --- this should detect mount points for all Unix |
| 1130 |
and POSIX variants. On Windows, a mount point is considered to be a drive |
| 1131 |
letter root (e.g. ``c:\``), a UNC share (e.g. ``\\server\share``), or a |
| 1132 |
mounted filesystem directory. |
| 1133 |
|
| 1134 |
.. versionadded:: 3.7 |
| 1135 |
|
| 1136 |
.. versionchanged:: 3.12 |
| 1137 |
Windows support was added. |
| 1138 |
|
| 1139 |
.. method:: Path.is_socket() |
| 1140 |
|
| 1141 |
Return ``True`` if the path points to a Unix socket. ``False`` will be |
| 1142 |
returned if the path is invalid, inaccessible or missing, or if it points |
| 1143 |
to something other than a Unix socket. Use :meth:`Path.stat` to |
| 1144 |
distinguish between these cases. |
| 1145 |
|
| 1146 |
|
| 1147 |
.. method:: Path.is_fifo() |
| 1148 |
|
| 1149 |
Return ``True`` if the path points to a FIFO. ``False`` will be returned if |
| 1150 |
the path is invalid, inaccessible or missing, or if it points to something |
| 1151 |
other than a FIFO. Use :meth:`Path.stat` to distinguish between these |
| 1152 |
cases. |
| 1153 |
|
| 1154 |
|
| 1155 |
.. method:: Path.is_block_device() |
| 1156 |
|
| 1157 |
Return ``True`` if the path points to a block device. ``False`` will be |
| 1158 |
returned if the path is invalid, inaccessible or missing, or if it points |
| 1159 |
to something other than a block device. Use :meth:`Path.stat` to |
| 1160 |
distinguish between these cases. |
| 1161 |
|
| 1162 |
|
| 1163 |
.. method:: Path.is_char_device() |
| 1164 |
|
| 1165 |
Return ``True`` if the path points to a character device. ``False`` will be |
| 1166 |
returned if the path is invalid, inaccessible or missing, or if it points |
| 1167 |
to something other than a character device. Use :meth:`Path.stat` to |
| 1168 |
distinguish between these cases. |
| 1169 |
|
| 1170 |
|
| 1171 |
.. method:: Path.samefile(other_path) |
| 1172 |
|
| 1173 |
Return whether this path points to the same file as *other_path*, which |
| 1174 |
can be either a Path object, or a string. The semantics are similar |
| 1175 |
to :func:`os.path.samefile` and :func:`os.path.samestat`. |
| 1176 |
|
| 1177 |
An :exc:`OSError` can be raised if either file cannot be accessed for some |
| 1178 |
reason. |
| 1179 |
|
| 1180 |
:: |
| 1181 |
|
| 1182 |
>>> p = Path('spam') |
| 1183 |
>>> q = Path('eggs') |
| 1184 |
>>> p.samefile(q) |
| 1185 |
False |
| 1186 |
>>> p.samefile('spam') |
| 1187 |
True |
| 1188 |
|
| 1189 |
.. versionadded:: 3.5 |
| 1190 |
|
| 1191 |
|
| 1192 |
.. attribute:: Path.info |
| 1193 |
|
| 1194 |
A :class:`~pathlib.types.PathInfo` object that supports querying file type |
| 1195 |
information. The object exposes methods that cache their results, which can |
| 1196 |
help reduce the number of system calls needed when switching on file type. |
| 1197 |
For example:: |
| 1198 |
|
| 1199 |
>>> p = Path('src') |
| 1200 |
>>> if p.info.is_symlink(): |
| 1201 |
... print('symlink') |
| 1202 |
... elif p.info.is_dir(): |
| 1203 |
... print('directory') |
| 1204 |
... elif p.info.exists(): |
| 1205 |
... print('something else') |
| 1206 |
... else: |
| 1207 |
... print('not found') |
| 1208 |
... |
| 1209 |
directory |
| 1210 |
|
| 1211 |
If the path was generated from :meth:`Path.iterdir` then this attribute is |
| 1212 |
initialized with some information about the file type gleaned from scanning |
| 1213 |
the parent directory. Merely accessing :attr:`Path.info` does not perform |
| 1214 |
any filesystem queries. |
| 1215 |
|
| 1216 |
To fetch up-to-date information, it's best to call :meth:`Path.is_dir`, |
| 1217 |
:meth:`~Path.is_file` and :meth:`~Path.is_symlink` rather than methods of |
| 1218 |
this attribute. There is no way to reset the cache; instead you can create |
| 1219 |
a new path object with an empty info cache via ``p = Path(p)``. |
| 1220 |
|
| 1221 |
.. versionadded:: 3.14 |
| 1222 |
|
| 1223 |
|
| 1224 |
Reading and writing files |
| 1225 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1226 |
|
| 1227 |
|
| 1228 |
.. method:: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None) |
| 1229 |
|
| 1230 |
Open the file pointed to by the path, like the built-in :func:`open` |
| 1231 |
function does:: |
| 1232 |
|
| 1233 |
>>> p = Path('setup.py') |
| 1234 |
>>> with p.open() as f: |
| 1235 |
... f.readline() |
| 1236 |
... |
| 1237 |
'#!/usr/bin/env python3\n' |
| 1238 |
|
| 1239 |
|
| 1240 |
.. method:: Path.read_text(encoding=None, errors=None, newline=None) |
| 1241 |
|
| 1242 |
Return the decoded contents of the pointed-to file as a string:: |
| 1243 |
|
| 1244 |
>>> p = Path('my_text_file') |
| 1245 |
>>> p.write_text('Text file contents') |
| 1246 |
18 |
| 1247 |
>>> p.read_text() |
| 1248 |
'Text file contents' |
| 1249 |
|
| 1250 |
The file is opened and then closed. The optional parameters have the same |
| 1251 |
meaning as in :func:`open`. |
| 1252 |
|
| 1253 |
.. versionadded:: 3.5 |
| 1254 |
|
| 1255 |
.. versionchanged:: 3.13 |
| 1256 |
The *newline* parameter was added. |
| 1257 |
|
| 1258 |
|
| 1259 |
.. method:: Path.read_bytes() |
| 1260 |
|
| 1261 |
Return the binary contents of the pointed-to file as a bytes object:: |
| 1262 |
|
| 1263 |
>>> p = Path('my_binary_file') |
| 1264 |
>>> p.write_bytes(b'Binary file contents') |
| 1265 |
20 |
| 1266 |
>>> p.read_bytes() |
| 1267 |
b'Binary file contents' |
| 1268 |
|
| 1269 |
.. versionadded:: 3.5 |
| 1270 |
|
| 1271 |
|
| 1272 |
.. method:: Path.write_text(data, encoding=None, errors=None, newline=None) |
| 1273 |
|
| 1274 |
Open the file pointed to in text mode, write *data* to it, and close the |
| 1275 |
file:: |
| 1276 |
|
| 1277 |
>>> p = Path('my_text_file') |
| 1278 |
>>> p.write_text('Text file contents') |
| 1279 |
18 |
| 1280 |
>>> p.read_text() |
| 1281 |
'Text file contents' |
| 1282 |
|
| 1283 |
An existing file of the same name is overwritten. The optional parameters |
| 1284 |
have the same meaning as in :func:`open`. |
| 1285 |
|
| 1286 |
.. versionadded:: 3.5 |
| 1287 |
|
| 1288 |
.. versionchanged:: 3.10 |
| 1289 |
The *newline* parameter was added. |
| 1290 |
|
| 1291 |
|
| 1292 |
.. method:: Path.write_bytes(data) |
| 1293 |
|
| 1294 |
Open the file pointed to in bytes mode, write *data* to it, and close the |
| 1295 |
file:: |
| 1296 |
|
| 1297 |
>>> p = Path('my_binary_file') |
| 1298 |
>>> p.write_bytes(b'Binary file contents') |
| 1299 |
20 |
| 1300 |
>>> p.read_bytes() |
| 1301 |
b'Binary file contents' |
| 1302 |
|
| 1303 |
An existing file of the same name is overwritten. |
| 1304 |
|
| 1305 |
.. versionadded:: 3.5 |
| 1306 |
|
| 1307 |
|
| 1308 |
Reading directories |
| 1309 |
^^^^^^^^^^^^^^^^^^^ |
| 1310 |
|
| 1311 |
.. method:: Path.iterdir() |
| 1312 |
|
| 1313 |
When the path points to a directory, yield path objects of the directory |
| 1314 |
contents:: |
| 1315 |
|
| 1316 |
>>> p = Path('docs') |
| 1317 |
>>> for child in p.iterdir(): child |
| 1318 |
... |
| 1319 |
PosixPath('docs/conf.py') |
| 1320 |
PosixPath('docs/_templates') |
| 1321 |
PosixPath('docs/make.bat') |
| 1322 |
PosixPath('docs/index.rst') |
| 1323 |
PosixPath('docs/_build') |
| 1324 |
PosixPath('docs/_static') |
| 1325 |
PosixPath('docs/Makefile') |
| 1326 |
|
| 1327 |
The children are yielded in arbitrary order, and the special entries |
| 1328 |
``'.'`` and ``'..'`` are not included. If a file is removed from or added |
| 1329 |
to the directory after creating the iterator, it is unspecified whether |
| 1330 |
a path object for that file is included. |
| 1331 |
|
| 1332 |
If the path is not a directory or otherwise inaccessible, :exc:`OSError` is |
| 1333 |
raised. |
| 1334 |
|
| 1335 |
|
| 1336 |
.. method:: Path.glob(pattern, *, case_sensitive=None, recurse_symlinks=False) |
| 1337 |
|
| 1338 |
Glob the given relative *pattern* in the directory represented by this path, |
| 1339 |
yielding all matching files (of any kind):: |
| 1340 |
|
| 1341 |
>>> sorted(Path('.').glob('*.py')) |
| 1342 |
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')] |
| 1343 |
>>> sorted(Path('.').glob('*/*.py')) |
| 1344 |
[PosixPath('docs/conf.py')] |
| 1345 |
>>> sorted(Path('.').glob('**/*.py')) |
| 1346 |
[PosixPath('build/lib/pathlib.py'), |
| 1347 |
PosixPath('docs/conf.py'), |
| 1348 |
PosixPath('pathlib.py'), |
| 1349 |
PosixPath('setup.py'), |
| 1350 |
PosixPath('test_pathlib.py')] |
| 1351 |
|
| 1352 |
.. note:: |
| 1353 |
The paths are returned in no particular order. |
| 1354 |
If you need a specific order, sort the results. |
| 1355 |
|
| 1356 |
.. seealso:: |
| 1357 |
:ref:`pathlib-pattern-language` documentation. |
| 1358 |
|
| 1359 |
By default, or when the *case_sensitive* keyword-only argument is set to |
| 1360 |
``None``, this method matches paths using platform-specific casing rules: |
| 1361 |
typically, case-sensitive on POSIX, and case-insensitive on Windows. |
| 1362 |
Set *case_sensitive* to ``True`` or ``False`` to override this behaviour. |
| 1363 |
|
| 1364 |
By default, or when the *recurse_symlinks* keyword-only argument is set to |
| 1365 |
``False``, this method follows symlinks except when expanding "``**``" |
| 1366 |
wildcards. Set *recurse_symlinks* to ``True`` to always follow symlinks. |
| 1367 |
|
| 1368 |
.. note:: |
| 1369 |
Any :exc:`OSError` exceptions raised from scanning the filesystem are |
| 1370 |
suppressed. This includes :exc:`PermissionError` when accessing |
| 1371 |
directories without read permission. |
| 1372 |
|
| 1373 |
.. audit-event:: pathlib.Path.glob self,pattern pathlib.Path.glob |
| 1374 |
|
| 1375 |
.. versionchanged:: 3.12 |
| 1376 |
The *case_sensitive* parameter was added. |
| 1377 |
|
| 1378 |
.. versionchanged:: 3.13 |
| 1379 |
The *recurse_symlinks* parameter was added. |
| 1380 |
|
| 1381 |
.. versionchanged:: 3.13 |
| 1382 |
The *pattern* parameter accepts a :term:`path-like object`. |
| 1383 |
|
| 1384 |
.. versionchanged:: 3.13 |
| 1385 |
Any :exc:`OSError` exceptions raised from scanning the filesystem are |
| 1386 |
suppressed. In previous versions, such exceptions are suppressed in many |
| 1387 |
cases, but not all. |
| 1388 |
|
| 1389 |
|
| 1390 |
.. method:: Path.rglob(pattern, *, case_sensitive=None, recurse_symlinks=False) |
| 1391 |
|
| 1392 |
Glob the given relative *pattern* recursively. This is like calling |
| 1393 |
:func:`Path.glob` with "``**/``" added in front of the *pattern*. |
| 1394 |
|
| 1395 |
.. note:: |
| 1396 |
The paths are returned in no particular order. |
| 1397 |
If you need a specific order, sort the results. |
| 1398 |
|
| 1399 |
.. note:: |
| 1400 |
Any :exc:`OSError` exceptions raised from scanning the filesystem are |
| 1401 |
suppressed. This includes :exc:`PermissionError` when accessing |
| 1402 |
directories without read permission. |
| 1403 |
|
| 1404 |
.. seealso:: |
| 1405 |
:ref:`pathlib-pattern-language` and :meth:`Path.glob` documentation. |
| 1406 |
|
| 1407 |
.. audit-event:: pathlib.Path.rglob self,pattern pathlib.Path.rglob |
| 1408 |
|
| 1409 |
.. versionchanged:: 3.12 |
| 1410 |
The *case_sensitive* parameter was added. |
| 1411 |
|
| 1412 |
.. versionchanged:: 3.13 |
| 1413 |
The *recurse_symlinks* parameter was added. |
| 1414 |
|
| 1415 |
.. versionchanged:: 3.13 |
| 1416 |
The *pattern* parameter accepts a :term:`path-like object`. |
| 1417 |
|
| 1418 |
|
| 1419 |
.. method:: Path.walk(top_down=True, on_error=None, follow_symlinks=False) |
| 1420 |
|
| 1421 |
Generate the file names in a directory tree by walking the tree |
| 1422 |
either top-down or bottom-up. |
| 1423 |
|
| 1424 |
For each directory in the directory tree rooted at *self* (including |
| 1425 |
*self* but excluding '.' and '..'), the method yields a 3-tuple of |
| 1426 |
``(dirpath, dirnames, filenames)``. |
| 1427 |
|
| 1428 |
*dirpath* is a :class:`Path` to the directory currently being walked, |
| 1429 |
*dirnames* is a list of strings for the names of subdirectories in *dirpath* |
| 1430 |
(excluding ``'.'`` and ``'..'``), and *filenames* is a list of strings for |
| 1431 |
the names of the non-directory files in *dirpath*. To get a full path |
| 1432 |
(which begins with *self*) to a file or directory in *dirpath*, do |
| 1433 |
``dirpath / name``. Whether or not the lists are sorted is file |
| 1434 |
system-dependent. |
| 1435 |
|
| 1436 |
If the optional argument *top_down* is true (which is the default), the triple for a |
| 1437 |
directory is generated before the triples for any of its subdirectories |
| 1438 |
(directories are walked top-down). If *top_down* is false, the triple |
| 1439 |
for a directory is generated after the triples for all of its subdirectories |
| 1440 |
(directories are walked bottom-up). No matter the value of *top_down*, the |
| 1441 |
list of subdirectories is retrieved before the triples for the directory and |
| 1442 |
its subdirectories are walked. |
| 1443 |
|
| 1444 |
When *top_down* is true, the caller can modify the *dirnames* list in-place |
| 1445 |
(for example, using :keyword:`del` or slice assignment), and :meth:`Path.walk` |
| 1446 |
will only recurse into the subdirectories whose names remain in *dirnames*. |
| 1447 |
This can be used to prune the search, or to impose a specific order of visiting, |
| 1448 |
or even to inform :meth:`Path.walk` about directories the caller creates or |
| 1449 |
renames before it resumes :meth:`Path.walk` again. Modifying *dirnames* when |
| 1450 |
*top_down* is false has no effect on the behavior of :meth:`Path.walk` since the |
| 1451 |
directories in *dirnames* have already been generated by the time *dirnames* |
| 1452 |
is yielded to the caller. |
| 1453 |
|
| 1454 |
By default, errors from :func:`os.scandir` are ignored. If the optional |
| 1455 |
argument *on_error* is specified, it should be a callable; it will be |
| 1456 |
called with one argument, an :exc:`OSError` instance. The callable can handle the |
| 1457 |
error to continue the walk or re-raise it to stop the walk. Note that the |
| 1458 |
filename is available as the ``filename`` attribute of the exception object. |
| 1459 |
|
| 1460 |
By default, :meth:`Path.walk` does not follow symbolic links, and instead adds them |
| 1461 |
to the *filenames* list. Set *follow_symlinks* to true to resolve symlinks |
| 1462 |
and place them in *dirnames* and *filenames* as appropriate for their targets, and |
| 1463 |
consequently visit directories pointed to by symlinks (where supported). |
| 1464 |
|
| 1465 |
.. note:: |
| 1466 |
|
| 1467 |
Be aware that setting *follow_symlinks* to true can lead to infinite |
| 1468 |
recursion if a link points to a parent directory of itself. :meth:`Path.walk` |
| 1469 |
does not keep track of the directories it has already visited. |
| 1470 |
|
| 1471 |
.. note:: |
| 1472 |
:meth:`Path.walk` assumes the directories it walks are not modified during |
| 1473 |
execution. For example, if a directory from *dirnames* has been replaced |
| 1474 |
with a symlink and *follow_symlinks* is false, :meth:`Path.walk` will |
| 1475 |
still try to descend into it. To prevent such behavior, remove directories |
| 1476 |
from *dirnames* as appropriate. |
| 1477 |
|
| 1478 |
.. note:: |
| 1479 |
|
| 1480 |
Unlike :func:`os.walk`, :meth:`Path.walk` lists symlinks to directories in |
| 1481 |
*filenames* if *follow_symlinks* is false. |
| 1482 |
|
| 1483 |
This example displays the number of bytes used by all files in each directory, |
| 1484 |
while ignoring ``__pycache__`` directories:: |
| 1485 |
|
| 1486 |
from pathlib import Path |
| 1487 |
for root, dirs, files in Path("cpython/Lib/concurrent").walk(on_error=print): |
| 1488 |
print( |
| 1489 |
root, |
| 1490 |
"consumes", |
| 1491 |
sum((root / file).stat().st_size for file in files), |
| 1492 |
"bytes in", |
| 1493 |
len(files), |
| 1494 |
"non-directory files" |
| 1495 |
) |
| 1496 |
if '__pycache__' in dirs: |
| 1497 |
dirs.remove('__pycache__') |
| 1498 |
|
| 1499 |
This next example is a simple implementation of :func:`shutil.rmtree`. |
| 1500 |
Walking the tree bottom-up is essential as :func:`rmdir` doesn't allow |
| 1501 |
deleting a directory before it is empty:: |
| 1502 |
|
| 1503 |
# Delete everything reachable from the directory "top". |
| 1504 |
# CAUTION: This is dangerous! For example, if top == Path('/'), |
| 1505 |
# it could delete all of your files. |
| 1506 |
for root, dirs, files in top.walk(top_down=False): |
| 1507 |
for name in files: |
| 1508 |
(root / name).unlink() |
| 1509 |
for name in dirs: |
| 1510 |
(root / name).rmdir() |
| 1511 |
|
| 1512 |
.. versionadded:: 3.12 |
| 1513 |
|
| 1514 |
|
| 1515 |
Creating files and directories |
| 1516 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1517 |
|
| 1518 |
.. method:: Path.touch(mode=0o666, exist_ok=True) |
| 1519 |
|
| 1520 |
Create a file at this given path. If *mode* is given, it is combined |
| 1521 |
with the process's ``umask`` value to determine the file mode and access |
| 1522 |
flags. If the file already exists, the function succeeds when *exist_ok* |
| 1523 |
is true (and its modification time is updated to the current time), |
| 1524 |
otherwise :exc:`FileExistsError` is raised. |
| 1525 |
|
| 1526 |
.. seealso:: |
| 1527 |
The :meth:`~Path.open`, :meth:`~Path.write_text` and |
| 1528 |
:meth:`~Path.write_bytes` methods are often used to create files. |
| 1529 |
|
| 1530 |
|
| 1531 |
.. method:: Path.mkdir(mode=0o777, parents=False, exist_ok=False) |
| 1532 |
|
| 1533 |
Create a new directory at this given path. If *mode* is given, it is |
| 1534 |
combined with the process's ``umask`` value to determine the file mode |
| 1535 |
and access flags. If the path already exists, :exc:`FileExistsError` |
| 1536 |
is raised. |
| 1537 |
|
| 1538 |
If *parents* is true, any missing parents of this path are created |
| 1539 |
as needed; they are created with the default permissions without taking |
| 1540 |
*mode* into account (mimicking the POSIX ``mkdir -p`` command). |
| 1541 |
|
| 1542 |
If *parents* is false (the default), a missing parent raises |
| 1543 |
:exc:`FileNotFoundError`. |
| 1544 |
|
| 1545 |
If *exist_ok* is false (the default), :exc:`FileExistsError` is |
| 1546 |
raised if the target directory already exists. |
| 1547 |
|
| 1548 |
If *exist_ok* is true, :exc:`FileExistsError` will not be raised unless the given |
| 1549 |
path already exists in the file system and is not a directory (same |
| 1550 |
behavior as the POSIX ``mkdir -p`` command). |
| 1551 |
|
| 1552 |
.. versionchanged:: 3.5 |
| 1553 |
The *exist_ok* parameter was added. |
| 1554 |
|
| 1555 |
|
| 1556 |
.. method:: Path.symlink_to(target, target_is_directory=False) |
| 1557 |
|
| 1558 |
Make this path a symbolic link pointing to *target*. |
| 1559 |
|
| 1560 |
On Windows, a symlink represents either a file or a directory, and does not |
| 1561 |
morph to the target dynamically. If the target is present, the type of the |
| 1562 |
symlink will be created to match. Otherwise, the symlink will be created |
| 1563 |
as a directory if *target_is_directory* is true or a file symlink (the |
| 1564 |
default) otherwise. On non-Windows platforms, *target_is_directory* is ignored. |
| 1565 |
|
| 1566 |
:: |
| 1567 |
|
| 1568 |
>>> p = Path('mylink') |
| 1569 |
>>> p.symlink_to('setup.py') |
| 1570 |
>>> p.resolve() |
| 1571 |
PosixPath('/home/antoine/pathlib/setup.py') |
| 1572 |
>>> p.stat().st_size |
| 1573 |
956 |
| 1574 |
>>> p.lstat().st_size |
| 1575 |
8 |
| 1576 |
|
| 1577 |
.. note:: |
| 1578 |
The order of arguments (link, target) is the reverse |
| 1579 |
of :func:`os.symlink`'s. |
| 1580 |
|
| 1581 |
.. versionchanged:: 3.13 |
| 1582 |
Raises :exc:`UnsupportedOperation` if :func:`os.symlink` is not |
| 1583 |
available. In previous versions, :exc:`NotImplementedError` was raised. |
| 1584 |
|
| 1585 |
|
| 1586 |
.. method:: Path.hardlink_to(target) |
| 1587 |
|
| 1588 |
Make this path a hard link to the same file as *target*. |
| 1589 |
|
| 1590 |
.. note:: |
| 1591 |
The order of arguments (link, target) is the reverse |
| 1592 |
of :func:`os.link`'s. |
| 1593 |
|
| 1594 |
.. versionadded:: 3.10 |
| 1595 |
|
| 1596 |
.. versionchanged:: 3.13 |
| 1597 |
Raises :exc:`UnsupportedOperation` if :func:`os.link` is not |
| 1598 |
available. In previous versions, :exc:`NotImplementedError` was raised. |
| 1599 |
|
| 1600 |
|
| 1601 |
Copying, moving and deleting |
| 1602 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1603 |
|
| 1604 |
.. method:: Path.copy(target, *, follow_symlinks=True, preserve_metadata=False) |
| 1605 |
|
| 1606 |
Copy this file or directory tree to the given *target*, and return a new |
| 1607 |
:class:`!Path` instance pointing to *target*. |
| 1608 |
|
| 1609 |
If the source is a file, the target will be replaced if it is an existing |
| 1610 |
file. If the source is a symlink and *follow_symlinks* is true (the |
| 1611 |
default), the symlink's target is copied. Otherwise, the symlink is |
| 1612 |
recreated at the destination. |
| 1613 |
|
| 1614 |
If *preserve_metadata* is false (the default), only directory structures |
| 1615 |
and file data are guaranteed to be copied. Set *preserve_metadata* to true |
| 1616 |
to ensure that file and directory permissions, flags, last access and |
| 1617 |
modification times, and extended attributes are copied where supported. |
| 1618 |
This argument has no effect when copying files on Windows (where |
| 1619 |
metadata is always preserved). |
| 1620 |
|
| 1621 |
.. note:: |
| 1622 |
Where supported by the operating system and file system, this method |
| 1623 |
performs a lightweight copy, where data blocks are only copied when |
| 1624 |
modified. This is known as copy-on-write. |
| 1625 |
|
| 1626 |
.. versionadded:: 3.14 |
| 1627 |
|
| 1628 |
|
| 1629 |
.. method:: Path.copy_into(target_dir, *, follow_symlinks=True, \ |
| 1630 |
preserve_metadata=False) |
| 1631 |
|
| 1632 |
Copy this file or directory tree into the given *target_dir*, which should |
| 1633 |
be an existing directory. Other arguments are handled identically to |
| 1634 |
:meth:`Path.copy`. Returns a new :class:`!Path` instance pointing to the |
| 1635 |
copy. |
| 1636 |
|
| 1637 |
.. versionadded:: 3.14 |
| 1638 |
|
| 1639 |
|
| 1640 |
.. method:: Path.rename(target) |
| 1641 |
|
| 1642 |
Rename this file or directory to the given *target*, and return a new |
| 1643 |
:class:`!Path` instance pointing to *target*. On Unix, if *target* exists |
| 1644 |
and is a file, it will be replaced silently if the user has permission. |
| 1645 |
On Windows, if *target* exists, :exc:`FileExistsError` will be raised. |
| 1646 |
*target* can be either a string or another path object:: |
| 1647 |
|
| 1648 |
>>> p = Path('foo') |
| 1649 |
>>> p.open('w').write('some text') |
| 1650 |
9 |
| 1651 |
>>> target = Path('bar') |
| 1652 |
>>> p.rename(target) |
| 1653 |
PosixPath('bar') |
| 1654 |
>>> target.open().read() |
| 1655 |
'some text' |
| 1656 |
|
| 1657 |
The target path may be absolute or relative. Relative paths are interpreted |
| 1658 |
relative to the current working directory, *not* the directory of the |
| 1659 |
:class:`!Path` object. |
| 1660 |
|
| 1661 |
It is implemented in terms of :func:`os.rename` and gives the same guarantees. |
| 1662 |
|
| 1663 |
.. versionchanged:: 3.8 |
| 1664 |
Added return value, return the new :class:`!Path` instance. |
| 1665 |
|
| 1666 |
|
| 1667 |
.. method:: Path.replace(target) |
| 1668 |
|
| 1669 |
Rename this file or directory to the given *target*, and return a new |
| 1670 |
:class:`!Path` instance pointing to *target*. If *target* points to an |
| 1671 |
existing file or empty directory, it will be unconditionally replaced. |
| 1672 |
|
| 1673 |
The target path may be absolute or relative. Relative paths are interpreted |
| 1674 |
relative to the current working directory, *not* the directory of the |
| 1675 |
:class:`!Path` object. |
| 1676 |
|
| 1677 |
.. versionchanged:: 3.8 |
| 1678 |
Added return value, return the new :class:`!Path` instance. |
| 1679 |
|
| 1680 |
|
| 1681 |
.. method:: Path.move(target) |
| 1682 |
|
| 1683 |
Move this file or directory tree to the given *target*, and return a new |
| 1684 |
:class:`!Path` instance pointing to *target*. |
| 1685 |
|
| 1686 |
If the *target* doesn't exist it will be created. If both this path and the |
| 1687 |
*target* are existing files, then the target is overwritten. If both paths |
| 1688 |
point to the same file or directory, or the *target* is a non-empty |
| 1689 |
directory, then :exc:`OSError` is raised. |
| 1690 |
|
| 1691 |
If both paths are on the same filesystem, the move is performed with |
| 1692 |
:func:`os.replace`. Otherwise, this path is copied (preserving metadata and |
| 1693 |
symlinks) and then deleted. |
| 1694 |
|
| 1695 |
.. versionadded:: 3.14 |
| 1696 |
|
| 1697 |
|
| 1698 |
.. method:: Path.move_into(target_dir) |
| 1699 |
|
| 1700 |
Move this file or directory tree into the given *target_dir*, which should |
| 1701 |
be an existing directory. Returns a new :class:`!Path` instance pointing to |
| 1702 |
the moved path. |
| 1703 |
|
| 1704 |
.. versionadded:: 3.14 |
| 1705 |
|
| 1706 |
|
| 1707 |
.. method:: Path.unlink(missing_ok=False) |
| 1708 |
|
| 1709 |
Remove this file or symbolic link. If the path points to a directory, |
| 1710 |
use :func:`Path.rmdir` instead. |
| 1711 |
|
| 1712 |
If *missing_ok* is false (the default), :exc:`FileNotFoundError` is |
| 1713 |
raised if the path does not exist. |
| 1714 |
|
| 1715 |
If *missing_ok* is true, :exc:`FileNotFoundError` exceptions will be |
| 1716 |
ignored (same behavior as the POSIX ``rm -f`` command). |
| 1717 |
|
| 1718 |
.. versionchanged:: 3.8 |
| 1719 |
The *missing_ok* parameter was added. |
| 1720 |
|
| 1721 |
|
| 1722 |
.. method:: Path.rmdir() |
| 1723 |
|
| 1724 |
Remove this directory. The directory must be empty. |
| 1725 |
|
| 1726 |
|
| 1727 |
Permissions and ownership |
| 1728 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1729 |
|
| 1730 |
.. method:: Path.owner(*, follow_symlinks=True) |
| 1731 |
|
| 1732 |
Return the name of the user owning the file. :exc:`KeyError` is raised |
| 1733 |
if the file's user identifier (UID) isn't found in the system database. |
| 1734 |
|
| 1735 |
This method normally follows symlinks; to get the owner of the symlink, add |
| 1736 |
the argument ``follow_symlinks=False``. |
| 1737 |
|
| 1738 |
.. versionchanged:: 3.13 |
| 1739 |
Raises :exc:`UnsupportedOperation` if the :mod:`pwd` module is not |
| 1740 |
available. In earlier versions, :exc:`NotImplementedError` was raised. |
| 1741 |
|
| 1742 |
.. versionchanged:: 3.13 |
| 1743 |
The *follow_symlinks* parameter was added. |
| 1744 |
|
| 1745 |
|
| 1746 |
.. method:: Path.group(*, follow_symlinks=True) |
| 1747 |
|
| 1748 |
Return the name of the group owning the file. :exc:`KeyError` is raised |
| 1749 |
if the file's group identifier (GID) isn't found in the system database. |
| 1750 |
|
| 1751 |
This method normally follows symlinks; to get the group of the symlink, add |
| 1752 |
the argument ``follow_symlinks=False``. |
| 1753 |
|
| 1754 |
.. versionchanged:: 3.13 |
| 1755 |
Raises :exc:`UnsupportedOperation` if the :mod:`grp` module is not |
| 1756 |
available. In earlier versions, :exc:`NotImplementedError` was raised. |
| 1757 |
|
| 1758 |
.. versionchanged:: 3.13 |
| 1759 |
The *follow_symlinks* parameter was added. |
| 1760 |
|
| 1761 |
|
| 1762 |
.. method:: Path.chmod(mode, *, follow_symlinks=True) |
| 1763 |
|
| 1764 |
Change the file mode and permissions, like :func:`os.chmod`. |
| 1765 |
|
| 1766 |
This method normally follows symlinks. Some Unix flavours support changing |
| 1767 |
permissions on the symlink itself; on these platforms you may add the |
| 1768 |
argument ``follow_symlinks=False``, or use :meth:`~Path.lchmod`. |
| 1769 |
|
| 1770 |
:: |
| 1771 |
|
| 1772 |
>>> p = Path('setup.py') |
| 1773 |
>>> p.stat().st_mode |
| 1774 |
33277 |
| 1775 |
>>> p.chmod(0o444) |
| 1776 |
>>> p.stat().st_mode |
| 1777 |
33060 |
| 1778 |
|
| 1779 |
.. versionchanged:: 3.10 |
| 1780 |
The *follow_symlinks* parameter was added. |
| 1781 |
|
| 1782 |
|
| 1783 |
.. method:: Path.lchmod(mode) |
| 1784 |
|
| 1785 |
Like :meth:`Path.chmod` but, if the path points to a symbolic link, the |
| 1786 |
symbolic link's mode is changed rather than its target's. |
| 1787 |
|
| 1788 |
|
| 1789 |
.. _pathlib-pattern-language: |
| 1790 |
|
| 1791 |
Pattern language |
| 1792 |
---------------- |
| 1793 |
|
| 1794 |
The following wildcards are supported in patterns for |
| 1795 |
:meth:`~PurePath.full_match`, :meth:`~Path.glob` and :meth:`~Path.rglob`: |
| 1796 |
|
| 1797 |
``**`` (entire segment) |
| 1798 |
Matches any number of file or directory segments, including zero. |
| 1799 |
``*`` (entire segment) |
| 1800 |
Matches one file or directory segment. |
| 1801 |
``*`` (part of a segment) |
| 1802 |
Matches any number of non-separator characters, including zero. |
| 1803 |
``?`` |
| 1804 |
Matches one non-separator character. |
| 1805 |
``[seq]`` |
| 1806 |
Matches one character in *seq*, where *seq* is a sequence of characters. |
| 1807 |
Range expressions are supported; for example, ``[a-z]`` matches any lowercase ASCII letter. |
| 1808 |
Multiple ranges can be combined: ``[a-zA-Z0-9_]`` matches any ASCII letter, digit, or underscore. |
| 1809 |
|
| 1810 |
``[!seq]`` |
| 1811 |
Matches one character not in *seq*, where *seq* follows the same rules as above. |
| 1812 |
|
| 1813 |
For a literal match, wrap the meta-characters in brackets. |
| 1814 |
For example, ``"[?]"`` matches the character ``"?"``. |
| 1815 |
|
| 1816 |
The "``**``" wildcard enables recursive globbing. A few examples: |
| 1817 |
|
| 1818 |
========================= =========================================== |
| 1819 |
Pattern Meaning |
| 1820 |
========================= =========================================== |
| 1821 |
"``**/*``" Any path with at least one segment. |
| 1822 |
"``**/*.py``" Any path with a final segment ending "``.py``". |
| 1823 |
"``assets/**``" Any path starting with "``assets/``". |
| 1824 |
"``assets/**/*``" Any path starting with "``assets/``", excluding "``assets/``" itself. |
| 1825 |
========================= =========================================== |
| 1826 |
|
| 1827 |
.. note:: |
| 1828 |
Globbing with the "``**``" wildcard visits every directory in the tree. |
| 1829 |
Large directory trees may take a long time to search. |
| 1830 |
|
| 1831 |
.. versionchanged:: 3.13 |
| 1832 |
Globbing with a pattern that ends with "``**``" returns both files and |
| 1833 |
directories. In previous versions, only directories were returned. |
| 1834 |
|
| 1835 |
In :meth:`Path.glob` and :meth:`~Path.rglob`, a trailing slash may be added to |
| 1836 |
the pattern to match only directories. |
| 1837 |
|
| 1838 |
.. versionchanged:: 3.11 |
| 1839 |
Globbing with a pattern that ends with a pathname components separator |
| 1840 |
(:data:`~os.sep` or :data:`~os.altsep`) returns only directories. |
| 1841 |
|
| 1842 |
|
| 1843 |
Comparison to the :mod:`glob` module |
| 1844 |
------------------------------------ |
| 1845 |
|
| 1846 |
The patterns accepted and results generated by :meth:`Path.glob` and |
| 1847 |
:meth:`Path.rglob` differ slightly from those by the :mod:`glob` module: |
| 1848 |
|
| 1849 |
1. Files beginning with a dot are not special in pathlib. This is |
| 1850 |
like passing ``include_hidden=True`` to :func:`glob.glob`. |
| 1851 |
2. "``**``" pattern components are always recursive in pathlib. This is like |
| 1852 |
passing ``recursive=True`` to :func:`glob.glob`. |
| 1853 |
3. "``**``" pattern components do not follow symlinks by default in pathlib. |
| 1854 |
This behaviour has no equivalent in :func:`glob.glob`, but you can pass |
| 1855 |
``recurse_symlinks=True`` to :meth:`Path.glob` for compatible behaviour. |
| 1856 |
4. Like all :class:`PurePath` and :class:`Path` objects, the values returned |
| 1857 |
from :meth:`Path.glob` and :meth:`Path.rglob` don't include trailing |
| 1858 |
slashes. |
| 1859 |
5. The values returned from pathlib's ``path.glob()`` and ``path.rglob()`` |
| 1860 |
include the *path* as a prefix, unlike the results of |
| 1861 |
``glob.glob(root_dir=path)``. |
| 1862 |
6. The values returned from pathlib's ``path.glob()`` and ``path.rglob()`` |
| 1863 |
may include *path* itself, for example when globbing "``**``", whereas the |
| 1864 |
results of ``glob.glob(root_dir=path)`` never include an empty string that |
| 1865 |
would correspond to *path*. |
| 1866 |
|
| 1867 |
|
| 1868 |
Comparison to the :mod:`os` and :mod:`os.path` modules |
| 1869 |
------------------------------------------------------ |
| 1870 |
|
| 1871 |
pathlib implements path operations using :class:`PurePath` and :class:`Path` |
| 1872 |
objects, and so it's said to be *object-oriented*. On the other hand, the |
| 1873 |
:mod:`os` and :mod:`os.path` modules supply functions that work with low-level |
| 1874 |
``str`` and ``bytes`` objects, which is a more *procedural* approach. Some |
| 1875 |
users consider the object-oriented style to be more readable. |
| 1876 |
|
| 1877 |
Many functions in :mod:`os` and :mod:`os.path` support ``bytes`` paths and |
| 1878 |
:ref:`paths relative to directory descriptors <dir_fd>`. These features aren't |
| 1879 |
available in pathlib. |
| 1880 |
|
| 1881 |
Python's ``str`` and ``bytes`` types, and portions of the :mod:`os` and |
| 1882 |
:mod:`os.path` modules, are written in C and are very speedy. pathlib is |
| 1883 |
written in pure Python and is often slower, but rarely slow enough to matter. |
| 1884 |
|
| 1885 |
pathlib's path normalization is slightly more opinionated and consistent than |
| 1886 |
:mod:`os.path`. For example, whereas :func:`os.path.abspath` eliminates |
| 1887 |
"``..``" segments from a path, which may change its meaning if symlinks are |
| 1888 |
involved, :meth:`Path.absolute` preserves these segments for greater safety. |
| 1889 |
|
| 1890 |
pathlib's path normalization may render it unsuitable for some applications: |
| 1891 |
|
| 1892 |
1. pathlib normalizes ``Path("my_folder/")`` to ``Path("my_folder")``, which |
| 1893 |
changes a path's meaning when supplied to various operating system APIs and |
| 1894 |
command-line utilities. Specifically, the absence of a trailing separator |
| 1895 |
may allow the path to be resolved as either a file or directory, rather |
| 1896 |
than a directory only. |
| 1897 |
2. pathlib normalizes ``Path("./my_program")`` to ``Path("my_program")``, |
| 1898 |
which changes a path's meaning when used as an executable search path, such |
| 1899 |
as in a shell or when spawning a child process. Specifically, the absence |
| 1900 |
of a separator in the path may force it to be looked up in :envvar:`PATH` |
| 1901 |
rather than the current directory. |
| 1902 |
|
| 1903 |
As a consequence of these differences, pathlib is not a drop-in replacement |
| 1904 |
for :mod:`os.path`. |
| 1905 |
|
| 1906 |
|
| 1907 |
Corresponding tools |
| 1908 |
^^^^^^^^^^^^^^^^^^^ |
| 1909 |
|
| 1910 |
Below is a table mapping various :mod:`os` functions to their corresponding |
| 1911 |
:class:`PurePath`/:class:`Path` equivalent. |
| 1912 |
|
| 1913 |
===================================== ============================================== |
| 1914 |
:mod:`os` and :mod:`os.path` :mod:`!pathlib` |
| 1915 |
===================================== ============================================== |
| 1916 |
:func:`os.path.dirname` :attr:`PurePath.parent` |
| 1917 |
:func:`os.path.basename` :attr:`PurePath.name` |
| 1918 |
:func:`os.path.splitext` :attr:`PurePath.stem`, :attr:`PurePath.suffix` |
| 1919 |
:func:`os.path.join` :meth:`PurePath.joinpath` |
| 1920 |
:func:`os.path.isabs` :meth:`PurePath.is_absolute` |
| 1921 |
:func:`os.path.relpath` :meth:`PurePath.relative_to` [1]_ |
| 1922 |
:func:`os.path.expanduser` :meth:`Path.expanduser` [2]_ |
| 1923 |
:func:`os.path.realpath` :meth:`Path.resolve` |
| 1924 |
:func:`os.path.abspath` :meth:`Path.absolute` [3]_ |
| 1925 |
:func:`os.path.exists` :meth:`Path.exists` |
| 1926 |
:func:`os.path.isfile` :meth:`Path.is_file` |
| 1927 |
:func:`os.path.isdir` :meth:`Path.is_dir` |
| 1928 |
:func:`os.path.islink` :meth:`Path.is_symlink` |
| 1929 |
:func:`os.path.isjunction` :meth:`Path.is_junction` |
| 1930 |
:func:`os.path.ismount` :meth:`Path.is_mount` |
| 1931 |
:func:`os.path.samefile` :meth:`Path.samefile` |
| 1932 |
:func:`os.getcwd` :meth:`Path.cwd` |
| 1933 |
:func:`os.stat` :meth:`Path.stat` |
| 1934 |
:func:`os.lstat` :meth:`Path.lstat` |
| 1935 |
:func:`os.listdir` :meth:`Path.iterdir` |
| 1936 |
:func:`os.walk` :meth:`Path.walk` [4]_ |
| 1937 |
:func:`os.mkdir`, :func:`os.makedirs` :meth:`Path.mkdir` |
| 1938 |
:func:`os.link` :meth:`Path.hardlink_to` |
| 1939 |
:func:`os.symlink` :meth:`Path.symlink_to` |
| 1940 |
:func:`os.readlink` :meth:`Path.readlink` |
| 1941 |
:func:`os.rename` :meth:`Path.rename` |
| 1942 |
:func:`os.replace` :meth:`Path.replace` |
| 1943 |
:func:`os.remove`, :func:`os.unlink` :meth:`Path.unlink` |
| 1944 |
:func:`os.rmdir` :meth:`Path.rmdir` |
| 1945 |
:func:`os.chmod` :meth:`Path.chmod` |
| 1946 |
:func:`os.lchmod` :meth:`Path.lchmod` |
| 1947 |
===================================== ============================================== |
| 1948 |
|
| 1949 |
.. rubric:: Footnotes |
| 1950 |
|
| 1951 |
.. [1] :func:`os.path.relpath` calls :func:`~os.path.abspath` to make paths |
| 1952 |
absolute and remove "``..``" parts, whereas :meth:`PurePath.relative_to` |
| 1953 |
is a lexical operation that raises :exc:`ValueError` when its inputs' |
| 1954 |
anchors differ (e.g. if one path is absolute and the other relative.) |
| 1955 |
.. [2] :func:`os.path.expanduser` returns the path unchanged if the home |
| 1956 |
directory can't be resolved, whereas :meth:`Path.expanduser` raises |
| 1957 |
:exc:`RuntimeError`. |
| 1958 |
.. [3] :func:`os.path.abspath` removes "``..``" components without resolving |
| 1959 |
symlinks, which may change the meaning of the path, whereas |
| 1960 |
:meth:`Path.absolute` leaves any "``..``" components in the path. |
| 1961 |
.. [4] :func:`os.walk` always follows symlinks when categorizing paths into |
| 1962 |
*dirnames* and *filenames*, whereas :meth:`Path.walk` categorizes all |
| 1963 |
symlinks into *filenames* when *follow_symlinks* is false (the default.) |
| 1964 |
|
| 1965 |
|
| 1966 |
Protocols |
| 1967 |
--------- |
| 1968 |
|
| 1969 |
.. module:: pathlib.types |
| 1970 |
:synopsis: pathlib types for static type checking |
| 1971 |
|
| 1972 |
|
| 1973 |
The :mod:`!pathlib.types` module provides types for static type checking. |
| 1974 |
|
| 1975 |
.. versionadded:: 3.14 |
| 1976 |
|
| 1977 |
|
| 1978 |
.. class:: PathInfo() |
| 1979 |
|
| 1980 |
A :class:`typing.Protocol` describing the |
| 1981 |
:attr:`Path.info <pathlib.Path.info>` attribute. Implementations may |
| 1982 |
return cached results from their methods. |
| 1983 |
|
| 1984 |
.. method:: exists(*, follow_symlinks=True) |
| 1985 |
|
| 1986 |
Return ``True`` if the path is an existing file or directory, or any |
| 1987 |
other kind of file; return ``False`` if the path doesn't exist. |
| 1988 |
|
| 1989 |
If *follow_symlinks* is ``False``, return ``True`` for symlinks without |
| 1990 |
checking if their targets exist. |
| 1991 |
|
| 1992 |
.. method:: is_dir(*, follow_symlinks=True) |
| 1993 |
|
| 1994 |
Return ``True`` if the path is a directory, or a symbolic link pointing |
| 1995 |
to a directory; return ``False`` if the path is (or points to) any other |
| 1996 |
kind of file, or if it doesn't exist. |
| 1997 |
|
| 1998 |
If *follow_symlinks* is ``False``, return ``True`` only if the path |
| 1999 |
is a directory (without following symlinks); return ``False`` if the |
| 2000 |
path is any other kind of file, or if it doesn't exist. |
| 2001 |
|
| 2002 |
.. method:: is_file(*, follow_symlinks=True) |
| 2003 |
|
| 2004 |
Return ``True`` if the path is a file, or a symbolic link pointing to |
| 2005 |
a file; return ``False`` if the path is (or points to) a directory or |
| 2006 |
other non-file, or if it doesn't exist. |
| 2007 |
|
| 2008 |
If *follow_symlinks* is ``False``, return ``True`` only if the path |
| 2009 |
is a file (without following symlinks); return ``False`` if the path |
| 2010 |
is a directory or other non-file, or if it doesn't exist. |
| 2011 |
|
| 2012 |
.. method:: is_symlink() |
| 2013 |
|
| 2014 |
Return ``True`` if the path is a symbolic link (even if broken); return |
| 2015 |
``False`` if the path is a directory or any kind of file, or if it |
| 2016 |
doesn't exist. |