1 2:mod:`pathlib` --- Object-oriented filesystem paths 3=================================================== 4 5.. module:: pathlib 6 :synopsis: Object-oriented filesystem paths 7 8.. versionadded:: 3.4 9 10**Source code:** :source:`Lib/pathlib.py` 11 12.. index:: single: path; operations 13 14-------------- 15 16This module offers classes representing filesystem paths with semantics 17appropriate for different operating systems. Path classes are divided 18between :ref:`pure paths <pure-paths>`, which provide purely computational 19operations without I/O, and :ref:`concrete paths <concrete-paths>`, which 20inherit from pure paths but also provide I/O operations. 21 22.. image:: pathlib-inheritance.png 23 :align: center 24 25If you've never used this module before or just aren't sure which class is 26right for your task, :class:`Path` is most likely what you need. It instantiates 27a :ref:`concrete path <concrete-paths>` for the platform the code is running on. 28 29Pure paths are useful in some special cases; for example: 30 31#. If you want to manipulate Windows paths on a Unix machine (or vice versa). 32 You cannot instantiate a :class:`WindowsPath` when running on Unix, but you 33 can instantiate :class:`PureWindowsPath`. 34#. You want to make sure that your code only manipulates paths without actually 35 accessing the OS. In this case, instantiating one of the pure classes may be 36 useful since those simply don't have any OS-accessing operations. 37 38.. seealso:: 39 :pep:`428`: The pathlib module -- object-oriented filesystem paths. 40 41.. seealso:: 42 For low-level path manipulation on strings, you can also use the 43 :mod:`os.path` module. 44 45 46Basic use 47--------- 48 49Importing the main class:: 50 51 >>> from pathlib import Path 52 53Listing subdirectories:: 54 55 >>> p = Path('.') 56 >>> [x for x in p.iterdir() if x.is_dir()] 57 [PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'), 58 PosixPath('__pycache__'), PosixPath('build')] 59 60Listing Python source files in this directory tree:: 61 62 >>> list(p.glob('**/*.py')) 63 [PosixPath('test_pathlib.py'), PosixPath('setup.py'), 64 PosixPath('pathlib.py'), PosixPath('docs/conf.py'), 65 PosixPath('build/lib/pathlib.py')] 66 67Navigating inside a directory tree:: 68 69 >>> p = Path('/etc') 70 >>> q = p / 'init.d' / 'reboot' 71 >>> q 72 PosixPath('/etc/init.d/reboot') 73 >>> q.resolve() 74 PosixPath('/etc/rc.d/init.d/halt') 75 76Querying path properties:: 77 78 >>> q.exists() 79 True 80 >>> q.is_dir() 81 False 82 83Opening a file:: 84 85 >>> with q.open() as f: f.readline() 86 ... 87 '#!/bin/bash\n' 88 89 90.. _pure-paths: 91 92Pure paths 93---------- 94 95Pure path objects provide path-handling operations which don't actually 96access a filesystem. There are three ways to access these classes, which 97we also call *flavours*: 98 99.. class:: PurePath(*pathsegments) 100 101 A generic class that represents the system's path flavour (instantiating 102 it creates either a :class:`PurePosixPath` or a :class:`PureWindowsPath`):: 103 104 >>> PurePath('setup.py') # Running on a Unix machine 105 PurePosixPath('setup.py') 106 107 Each element of *pathsegments* can be either a string representing a 108 path segment, an object implementing the :class:`os.PathLike` interface 109 which returns a string, or another path object:: 110 111 >>> PurePath('foo', 'some/path', 'bar') 112 PurePosixPath('foo/some/path/bar') 113 >>> PurePath(Path('foo'), Path('bar')) 114 PurePosixPath('foo/bar') 115 116 When *pathsegments* is empty, the current directory is assumed:: 117 118 >>> PurePath() 119 PurePosixPath('.') 120 121 When several absolute paths are given, the last is taken as an anchor 122 (mimicking :func:`os.path.join`'s behaviour):: 123 124 >>> PurePath('/etc', '/usr', 'lib64') 125 PurePosixPath('/usr/lib64') 126 >>> PureWindowsPath('c:/Windows', 'd:bar') 127 PureWindowsPath('d:bar') 128 129 However, in a Windows path, changing the local root doesn't discard the 130 previous drive setting:: 131 132 >>> PureWindowsPath('c:/Windows', '/Program Files') 133 PureWindowsPath('c:/Program Files') 134 135 Spurious slashes and single dots are collapsed, but double dots (``'..'``) 136 are not, since this would change the meaning of a path in the face of 137 symbolic links:: 138 139 >>> PurePath('foo//bar') 140 PurePosixPath('foo/bar') 141 >>> PurePath('foo/./bar') 142 PurePosixPath('foo/bar') 143 >>> PurePath('foo/../bar') 144 PurePosixPath('foo/../bar') 145 146 (a naïve approach would make ``PurePosixPath('foo/../bar')`` equivalent 147 to ``PurePosixPath('bar')``, which is wrong if ``foo`` is a symbolic link 148 to another directory) 149 150 Pure path objects implement the :class:`os.PathLike` interface, allowing them 151 to be used anywhere the interface is accepted. 152 153 .. versionchanged:: 3.6 154 Added support for the :class:`os.PathLike` interface. 155 156.. class:: PurePosixPath(*pathsegments) 157 158 A subclass of :class:`PurePath`, this path flavour represents non-Windows 159 filesystem paths:: 160 161 >>> PurePosixPath('/etc') 162 PurePosixPath('/etc') 163 164 *pathsegments* is specified similarly to :class:`PurePath`. 165 166.. class:: PureWindowsPath(*pathsegments) 167 168 A subclass of :class:`PurePath`, this path flavour represents Windows 169 filesystem paths:: 170 171 >>> PureWindowsPath('c:/Program Files/') 172 PureWindowsPath('c:/Program Files') 173 174 *pathsegments* is specified similarly to :class:`PurePath`. 175 176Regardless of the system you're running on, you can instantiate all of 177these classes, since they don't provide any operation that does system calls. 178 179 180General properties 181^^^^^^^^^^^^^^^^^^ 182 183Paths are immutable and hashable. Paths of a same flavour are comparable 184and orderable. These properties respect the flavour's case-folding 185semantics:: 186 187 >>> PurePosixPath('foo') == PurePosixPath('FOO') 188 False 189 >>> PureWindowsPath('foo') == PureWindowsPath('FOO') 190 True 191 >>> PureWindowsPath('FOO') in { PureWindowsPath('foo') } 192 True 193 >>> PureWindowsPath('C:') < PureWindowsPath('d:') 194 True 195 196Paths of a different flavour compare unequal and cannot be ordered:: 197 198 >>> PureWindowsPath('foo') == PurePosixPath('foo') 199 False 200 >>> PureWindowsPath('foo') < PurePosixPath('foo') 201 Traceback (most recent call last): 202 File "<stdin>", line 1, in <module> 203 TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath' 204 205 206Operators 207^^^^^^^^^ 208 209The slash operator helps create child paths, similarly to :func:`os.path.join`:: 210 211 >>> p = PurePath('/etc') 212 >>> p 213 PurePosixPath('/etc') 214 >>> p / 'init.d' / 'apache2' 215 PurePosixPath('/etc/init.d/apache2') 216 >>> q = PurePath('bin') 217 >>> '/usr' / q 218 PurePosixPath('/usr/bin') 219 220A path object can be used anywhere an object implementing :class:`os.PathLike` 221is accepted:: 222 223 >>> import os 224 >>> p = PurePath('/etc') 225 >>> os.fspath(p) 226 '/etc' 227 228The string representation of a path is the raw filesystem path itself 229(in native form, e.g. with backslashes under Windows), which you can 230pass to any function taking a file path as a string:: 231 232 >>> p = PurePath('/etc') 233 >>> str(p) 234 '/etc' 235 >>> p = PureWindowsPath('c:/Program Files') 236 >>> str(p) 237 'c:\\Program Files' 238 239Similarly, calling :class:`bytes` on a path gives the raw filesystem path as a 240bytes object, as encoded by :func:`os.fsencode`:: 241 242 >>> bytes(p) 243 b'/etc' 244 245.. note:: 246 Calling :class:`bytes` is only recommended under Unix. Under Windows, 247 the unicode form is the canonical representation of filesystem paths. 248 249 250Accessing individual parts 251^^^^^^^^^^^^^^^^^^^^^^^^^^ 252 253To access the individual "parts" (components) of a path, use the following 254property: 255 256.. data:: PurePath.parts 257 258 A tuple giving access to the path's various components:: 259 260 >>> p = PurePath('/usr/bin/python3') 261 >>> p.parts 262 ('/', 'usr', 'bin', 'python3') 263 264 >>> p = PureWindowsPath('c:/Program Files/PSF') 265 >>> p.parts 266 ('c:\\', 'Program Files', 'PSF') 267 268 (note how the drive and local root are regrouped in a single part) 269 270 271Methods and properties 272^^^^^^^^^^^^^^^^^^^^^^ 273 274.. testsetup:: 275 276 from pathlib import PurePath, PurePosixPath, PureWindowsPath 277 278Pure paths provide the following methods and properties: 279 280.. data:: PurePath.drive 281 282 A string representing the drive letter or name, if any:: 283 284 >>> PureWindowsPath('c:/Program Files/').drive 285 'c:' 286 >>> PureWindowsPath('/Program Files/').drive 287 '' 288 >>> PurePosixPath('/etc').drive 289 '' 290 291 UNC shares are also considered drives:: 292 293 >>> PureWindowsPath('//host/share/foo.txt').drive 294 '\\\\host\\share' 295 296.. data:: PurePath.root 297 298 A string representing the (local or global) root, if any:: 299 300 >>> PureWindowsPath('c:/Program Files/').root 301 '\\' 302 >>> PureWindowsPath('c:Program Files/').root 303 '' 304 >>> PurePosixPath('/etc').root 305 '/' 306 307 UNC shares always have a root:: 308 309 >>> PureWindowsPath('//host/share').root 310 '\\' 311 312.. data:: PurePath.anchor 313 314 The concatenation of the drive and root:: 315 316 >>> PureWindowsPath('c:/Program Files/').anchor 317 'c:\\' 318 >>> PureWindowsPath('c:Program Files/').anchor 319 'c:' 320 >>> PurePosixPath('/etc').anchor 321 '/' 322 >>> PureWindowsPath('//host/share').anchor 323 '\\\\host\\share\\' 324 325 326.. data:: PurePath.parents 327 328 An immutable sequence providing access to the logical ancestors of 329 the path:: 330 331 >>> p = PureWindowsPath('c:/foo/bar/setup.py') 332 >>> p.parents[0] 333 PureWindowsPath('c:/foo/bar') 334 >>> p.parents[1] 335 PureWindowsPath('c:/foo') 336 >>> p.parents[2] 337 PureWindowsPath('c:/') 338 339 340.. data:: PurePath.parent 341 342 The logical parent of the path:: 343 344 >>> p = PurePosixPath('/a/b/c/d') 345 >>> p.parent 346 PurePosixPath('/a/b/c') 347 348 You cannot go past an anchor, or empty path:: 349 350 >>> p = PurePosixPath('/') 351 >>> p.parent 352 PurePosixPath('/') 353 >>> p = PurePosixPath('.') 354 >>> p.parent 355 PurePosixPath('.') 356 357 .. note:: 358 This is a purely lexical operation, hence the following behaviour:: 359 360 >>> p = PurePosixPath('foo/..') 361 >>> p.parent 362 PurePosixPath('foo') 363 364 If you want to walk an arbitrary filesystem path upwards, it is 365 recommended to first call :meth:`Path.resolve` so as to resolve 366 symlinks and eliminate `".."` components. 367 368 369.. data:: PurePath.name 370 371 A string representing the final path component, excluding the drive and 372 root, if any:: 373 374 >>> PurePosixPath('my/library/setup.py').name 375 'setup.py' 376 377 UNC drive names are not considered:: 378 379 >>> PureWindowsPath('//some/share/setup.py').name 380 'setup.py' 381 >>> PureWindowsPath('//some/share').name 382 '' 383 384 385.. data:: PurePath.suffix 386 387 The file extension of the final component, if any:: 388 389 >>> PurePosixPath('my/library/setup.py').suffix 390 '.py' 391 >>> PurePosixPath('my/library.tar.gz').suffix 392 '.gz' 393 >>> PurePosixPath('my/library').suffix 394 '' 395 396 397.. data:: PurePath.suffixes 398 399 A list of the path's file extensions:: 400 401 >>> PurePosixPath('my/library.tar.gar').suffixes 402 ['.tar', '.gar'] 403 >>> PurePosixPath('my/library.tar.gz').suffixes 404 ['.tar', '.gz'] 405 >>> PurePosixPath('my/library').suffixes 406 [] 407 408 409.. data:: PurePath.stem 410 411 The final path component, without its suffix:: 412 413 >>> PurePosixPath('my/library.tar.gz').stem 414 'library.tar' 415 >>> PurePosixPath('my/library.tar').stem 416 'library' 417 >>> PurePosixPath('my/library').stem 418 'library' 419 420 421.. method:: PurePath.as_posix() 422 423 Return a string representation of the path with forward slashes (``/``):: 424 425 >>> p = PureWindowsPath('c:\\windows') 426 >>> str(p) 427 'c:\\windows' 428 >>> p.as_posix() 429 'c:/windows' 430 431 432.. method:: PurePath.as_uri() 433 434 Represent the path as a ``file`` URI. :exc:`ValueError` is raised if 435 the path isn't absolute. 436 437 >>> p = PurePosixPath('/etc/passwd') 438 >>> p.as_uri() 439 'file:///etc/passwd' 440 >>> p = PureWindowsPath('c:/Windows') 441 >>> p.as_uri() 442 'file:///c:/Windows' 443 444 445.. method:: PurePath.is_absolute() 446 447 Return whether the path is absolute or not. A path is considered absolute 448 if it has both a root and (if the flavour allows) a drive:: 449 450 >>> PurePosixPath('/a/b').is_absolute() 451 True 452 >>> PurePosixPath('a/b').is_absolute() 453 False 454 455 >>> PureWindowsPath('c:/a/b').is_absolute() 456 True 457 >>> PureWindowsPath('/a/b').is_absolute() 458 False 459 >>> PureWindowsPath('c:').is_absolute() 460 False 461 >>> PureWindowsPath('//some/share').is_absolute() 462 True 463 464 465.. method:: PurePath.is_relative_to(*other) 466 467 Return whether or not this path is relative to the *other* path. 468 469 >>> p = PurePath('/etc/passwd') 470 >>> p.is_relative_to('/etc') 471 True 472 >>> p.is_relative_to('/usr') 473 False 474 475 .. versionadded:: 3.9 476 477 478.. method:: PurePath.is_reserved() 479 480 With :class:`PureWindowsPath`, return ``True`` if the path is considered 481 reserved under Windows, ``False`` otherwise. With :class:`PurePosixPath`, 482 ``False`` is always returned. 483 484 >>> PureWindowsPath('nul').is_reserved() 485 True 486 >>> PurePosixPath('nul').is_reserved() 487 False 488 489 File system calls on reserved paths can fail mysteriously or have 490 unintended effects. 491 492 493.. method:: PurePath.joinpath(*other) 494 495 Calling this method is equivalent to combining the path with each of 496 the *other* arguments in turn:: 497 498 >>> PurePosixPath('/etc').joinpath('passwd') 499 PurePosixPath('/etc/passwd') 500 >>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd')) 501 PurePosixPath('/etc/passwd') 502 >>> PurePosixPath('/etc').joinpath('init.d', 'apache2') 503 PurePosixPath('/etc/init.d/apache2') 504 >>> PureWindowsPath('c:').joinpath('/Program Files') 505 PureWindowsPath('c:/Program Files') 506 507 508.. method:: PurePath.match(pattern) 509 510 Match this path against the provided glob-style pattern. Return ``True`` 511 if matching is successful, ``False`` otherwise. 512 513 If *pattern* is relative, the path can be either relative or absolute, 514 and matching is done from the right:: 515 516 >>> PurePath('a/b.py').match('*.py') 517 True 518 >>> PurePath('/a/b/c.py').match('b/*.py') 519 True 520 >>> PurePath('/a/b/c.py').match('a/*.py') 521 False 522 523 If *pattern* is absolute, the path must be absolute, and the whole path 524 must match:: 525 526 >>> PurePath('/a.py').match('/*.py') 527 True 528 >>> PurePath('a/b.py').match('/*.py') 529 False 530 531 As with other methods, case-sensitivity follows platform defaults:: 532 533 >>> PurePosixPath('b.py').match('*.PY') 534 False 535 >>> PureWindowsPath('b.py').match('*.PY') 536 True 537 538 539.. method:: PurePath.relative_to(*other) 540 541 Compute a version of this path relative to the path represented by 542 *other*. If it's impossible, ValueError is raised:: 543 544 >>> p = PurePosixPath('/etc/passwd') 545 >>> p.relative_to('/') 546 PurePosixPath('etc/passwd') 547 >>> p.relative_to('/etc') 548 PurePosixPath('passwd') 549 >>> p.relative_to('/usr') 550 Traceback (most recent call last): 551 File "<stdin>", line 1, in <module> 552 File "pathlib.py", line 694, in relative_to 553 .format(str(self), str(formatted))) 554 ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other absolute. 555 556 NOTE: This function is part of :class:`PurePath` and works with strings. It does not check or access the underlying file structure. 557 558 559.. method:: PurePath.with_name(name) 560 561 Return a new path with the :attr:`name` changed. If the original path 562 doesn't have a name, ValueError is raised:: 563 564 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') 565 >>> p.with_name('setup.py') 566 PureWindowsPath('c:/Downloads/setup.py') 567 >>> p = PureWindowsPath('c:/') 568 >>> p.with_name('setup.py') 569 Traceback (most recent call last): 570 File "<stdin>", line 1, in <module> 571 File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name 572 raise ValueError("%r has an empty name" % (self,)) 573 ValueError: PureWindowsPath('c:/') has an empty name 574 575 576.. method:: PurePath.with_stem(stem) 577 578 Return a new path with the :attr:`stem` changed. If the original path 579 doesn't have a name, ValueError is raised:: 580 581 >>> p = PureWindowsPath('c:/Downloads/draft.txt') 582 >>> p.with_stem('final') 583 PureWindowsPath('c:/Downloads/final.txt') 584 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') 585 >>> p.with_stem('lib') 586 PureWindowsPath('c:/Downloads/lib.gz') 587 >>> p = PureWindowsPath('c:/') 588 >>> p.with_stem('') 589 Traceback (most recent call last): 590 File "<stdin>", line 1, in <module> 591 File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem 592 return self.with_name(stem + self.suffix) 593 File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name 594 raise ValueError("%r has an empty name" % (self,)) 595 ValueError: PureWindowsPath('c:/') has an empty name 596 597 .. versionadded:: 3.9 598 599 600.. method:: PurePath.with_suffix(suffix) 601 602 Return a new path with the :attr:`suffix` changed. If the original path 603 doesn't have a suffix, the new *suffix* is appended instead. If the 604 *suffix* is an empty string, the original suffix is removed:: 605 606 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz') 607 >>> p.with_suffix('.bz2') 608 PureWindowsPath('c:/Downloads/pathlib.tar.bz2') 609 >>> p = PureWindowsPath('README') 610 >>> p.with_suffix('.txt') 611 PureWindowsPath('README.txt') 612 >>> p = PureWindowsPath('README.txt') 613 >>> p.with_suffix('') 614 PureWindowsPath('README') 615 616 617.. _concrete-paths: 618 619 620Concrete paths 621-------------- 622 623Concrete paths are subclasses of the pure path classes. In addition to 624operations provided by the latter, they also provide methods to do system 625calls on path objects. There are three ways to instantiate concrete paths: 626 627.. class:: Path(*pathsegments) 628 629 A subclass of :class:`PurePath`, this class represents concrete paths of 630 the system's path flavour (instantiating it creates either a 631 :class:`PosixPath` or a :class:`WindowsPath`):: 632 633 >>> Path('setup.py') 634 PosixPath('setup.py') 635 636 *pathsegments* is specified similarly to :class:`PurePath`. 637 638.. class:: PosixPath(*pathsegments) 639 640 A subclass of :class:`Path` and :class:`PurePosixPath`, this class 641 represents concrete non-Windows filesystem paths:: 642 643 >>> PosixPath('/etc') 644 PosixPath('/etc') 645 646 *pathsegments* is specified similarly to :class:`PurePath`. 647 648.. class:: WindowsPath(*pathsegments) 649 650 A subclass of :class:`Path` and :class:`PureWindowsPath`, this class 651 represents concrete Windows filesystem paths:: 652 653 >>> WindowsPath('c:/Program Files/') 654 WindowsPath('c:/Program Files') 655 656 *pathsegments* is specified similarly to :class:`PurePath`. 657 658You can only instantiate the class flavour that corresponds to your system 659(allowing system calls on non-compatible path flavours could lead to 660bugs or failures in your application):: 661 662 >>> import os 663 >>> os.name 664 'posix' 665 >>> Path('setup.py') 666 PosixPath('setup.py') 667 >>> PosixPath('setup.py') 668 PosixPath('setup.py') 669 >>> WindowsPath('setup.py') 670 Traceback (most recent call last): 671 File "<stdin>", line 1, in <module> 672 File "pathlib.py", line 798, in __new__ 673 % (cls.__name__,)) 674 NotImplementedError: cannot instantiate 'WindowsPath' on your system 675 676 677Methods 678^^^^^^^ 679 680Concrete paths provide the following methods in addition to pure paths 681methods. Many of these methods can raise an :exc:`OSError` if a system 682call fails (for example because the path doesn't exist). 683 684.. versionchanged:: 3.8 685 686 :meth:`~Path.exists()`, :meth:`~Path.is_dir()`, :meth:`~Path.is_file()`, 687 :meth:`~Path.is_mount()`, :meth:`~Path.is_symlink()`, 688 :meth:`~Path.is_block_device()`, :meth:`~Path.is_char_device()`, 689 :meth:`~Path.is_fifo()`, :meth:`~Path.is_socket()` now return ``False`` 690 instead of raising an exception for paths that contain characters 691 unrepresentable at the OS level. 692 693 694.. classmethod:: Path.cwd() 695 696 Return a new path object representing the current directory (as returned 697 by :func:`os.getcwd`):: 698 699 >>> Path.cwd() 700 PosixPath('/home/antoine/pathlib') 701 702 703.. classmethod:: Path.home() 704 705 Return a new path object representing the user's home directory (as 706 returned by :func:`os.path.expanduser` with ``~`` construct):: 707 708 >>> Path.home() 709 PosixPath('/home/antoine') 710 711 Note that unlike :func:`os.path.expanduser`, on POSIX systems a 712 :exc:`KeyError` or :exc:`RuntimeError` will be raised, and on Windows systems a 713 :exc:`RuntimeError` will be raised if home directory can't be resolved. 714 715 .. versionadded:: 3.5 716 717 718.. method:: Path.stat() 719 720 Return a :class:`os.stat_result` object containing information about this path, like :func:`os.stat`. 721 The result is looked up at each call to this method. 722 723 :: 724 725 >>> p = Path('setup.py') 726 >>> p.stat().st_size 727 956 728 >>> p.stat().st_mtime 729 1327883547.852554 730 731 732.. method:: Path.chmod(mode) 733 734 Change the file mode and permissions, like :func:`os.chmod`:: 735 736 >>> p = Path('setup.py') 737 >>> p.stat().st_mode 738 33277 739 >>> p.chmod(0o444) 740 >>> p.stat().st_mode 741 33060 742 743 744.. method:: Path.exists() 745 746 Whether the path points to an existing file or directory:: 747 748 >>> Path('.').exists() 749 True 750 >>> Path('setup.py').exists() 751 True 752 >>> Path('/etc').exists() 753 True 754 >>> Path('nonexistentfile').exists() 755 False 756 757 .. note:: 758 If the path points to a symlink, :meth:`exists` returns whether the 759 symlink *points to* an existing file or directory. 760 761 762.. method:: Path.expanduser() 763 764 Return a new path with expanded ``~`` and ``~user`` constructs, 765 as returned by :meth:`os.path.expanduser`:: 766 767 >>> p = PosixPath('~/films/Monty Python') 768 >>> p.expanduser() 769 PosixPath('/home/eric/films/Monty Python') 770 771 Note that unlike :func:`os.path.expanduser`, on POSIX systems a 772 :exc:`KeyError` or :exc:`RuntimeError` will be raised, and on Windows systems a 773 :exc:`RuntimeError` will be raised if home directory can't be resolved. 774 775 .. versionadded:: 3.5 776 777 778.. method:: Path.glob(pattern) 779 780 Glob the given relative *pattern* in the directory represented by this path, 781 yielding all matching files (of any kind):: 782 783 >>> sorted(Path('.').glob('*.py')) 784 [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')] 785 >>> sorted(Path('.').glob('*/*.py')) 786 [PosixPath('docs/conf.py')] 787 788 The "``**``" pattern means "this directory and all subdirectories, 789 recursively". In other words, it enables recursive globbing:: 790 791 >>> sorted(Path('.').glob('**/*.py')) 792 [PosixPath('build/lib/pathlib.py'), 793 PosixPath('docs/conf.py'), 794 PosixPath('pathlib.py'), 795 PosixPath('setup.py'), 796 PosixPath('test_pathlib.py')] 797 798 .. note:: 799 Using the "``**``" pattern in large directory trees may consume 800 an inordinate amount of time. 801 802 .. audit-event:: pathlib.Path.glob self,pattern pathlib.Path.glob 803 804 805.. method:: Path.group() 806 807 Return the name of the group owning the file. :exc:`KeyError` is raised 808 if the file's gid isn't found in the system database. 809 810 811.. method:: Path.is_dir() 812 813 Return ``True`` if the path points to a directory (or a symbolic link 814 pointing to a directory), ``False`` if it points to another kind of file. 815 816 ``False`` is also returned if the path doesn't exist or is a broken symlink; 817 other errors (such as permission errors) are propagated. 818 819 820.. method:: Path.is_file() 821 822 Return ``True`` if the path points to a regular file (or a symbolic link 823 pointing to a regular file), ``False`` if it points to another kind of file. 824 825 ``False`` is also returned if the path doesn't exist or is a broken symlink; 826 other errors (such as permission errors) are propagated. 827 828 829.. method:: Path.is_mount() 830 831 Return ``True`` if the path is a :dfn:`mount point`: a point in a 832 file system where a different file system has been mounted. On POSIX, the 833 function checks whether *path*'s parent, :file:`path/..`, is on a different 834 device than *path*, or whether :file:`path/..` and *path* point to the same 835 i-node on the same device --- this should detect mount points for all Unix 836 and POSIX variants. Not implemented on Windows. 837 838 .. versionadded:: 3.7 839 840 841.. method:: Path.is_symlink() 842 843 Return ``True`` if the path points to a symbolic link, ``False`` otherwise. 844 845 ``False`` is also returned if the path doesn't exist; other errors (such 846 as permission errors) are propagated. 847 848 849.. method:: Path.is_socket() 850 851 Return ``True`` if the path points to a Unix socket (or a symbolic link 852 pointing to a Unix socket), ``False`` if it points to another kind of file. 853 854 ``False`` is also returned if the path doesn't exist or is a broken symlink; 855 other errors (such as permission errors) are propagated. 856 857 858.. method:: Path.is_fifo() 859 860 Return ``True`` if the path points to a FIFO (or a symbolic link 861 pointing to a FIFO), ``False`` if it points to another kind of file. 862 863 ``False`` is also returned if the path doesn't exist or is a broken symlink; 864 other errors (such as permission errors) are propagated. 865 866 867.. method:: Path.is_block_device() 868 869 Return ``True`` if the path points to a block device (or a symbolic link 870 pointing to a block device), ``False`` if it points to another kind of file. 871 872 ``False`` is also returned if the path doesn't exist or is a broken symlink; 873 other errors (such as permission errors) are propagated. 874 875 876.. method:: Path.is_char_device() 877 878 Return ``True`` if the path points to a character device (or a symbolic link 879 pointing to a character device), ``False`` if it points to another kind of file. 880 881 ``False`` is also returned if the path doesn't exist or is a broken symlink; 882 other errors (such as permission errors) are propagated. 883 884 885.. method:: Path.iterdir() 886 887 When the path points to a directory, yield path objects of the directory 888 contents:: 889 890 >>> p = Path('docs') 891 >>> for child in p.iterdir(): child 892 ... 893 PosixPath('docs/conf.py') 894 PosixPath('docs/_templates') 895 PosixPath('docs/make.bat') 896 PosixPath('docs/index.rst') 897 PosixPath('docs/_build') 898 PosixPath('docs/_static') 899 PosixPath('docs/Makefile') 900 901 The children are yielded in arbitrary order, and the special entries 902 ``'.'`` and ``'..'`` are not included. If a file is removed from or added 903 to the directory after creating the iterator, whether an path object for 904 that file be included is unspecified. 905 906.. method:: Path.lchmod(mode) 907 908 Like :meth:`Path.chmod` but, if the path points to a symbolic link, the 909 symbolic link's mode is changed rather than its target's. 910 911 912.. method:: Path.lstat() 913 914 Like :meth:`Path.stat` but, if the path points to a symbolic link, return 915 the symbolic link's information rather than its target's. 916 917 918.. method:: Path.mkdir(mode=0o777, parents=False, exist_ok=False) 919 920 Create a new directory at this given path. If *mode* is given, it is 921 combined with the process' ``umask`` value to determine the file mode 922 and access flags. If the path already exists, :exc:`FileExistsError` 923 is raised. 924 925 If *parents* is true, any missing parents of this path are created 926 as needed; they are created with the default permissions without taking 927 *mode* into account (mimicking the POSIX ``mkdir -p`` command). 928 929 If *parents* is false (the default), a missing parent raises 930 :exc:`FileNotFoundError`. 931 932 If *exist_ok* is false (the default), :exc:`FileExistsError` is 933 raised if the target directory already exists. 934 935 If *exist_ok* is true, :exc:`FileExistsError` exceptions will be 936 ignored (same behavior as the POSIX ``mkdir -p`` command), but only if the 937 last path component is not an existing non-directory file. 938 939 .. versionchanged:: 3.5 940 The *exist_ok* parameter was added. 941 942 943.. method:: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None) 944 945 Open the file pointed to by the path, like the built-in :func:`open` 946 function does:: 947 948 >>> p = Path('setup.py') 949 >>> with p.open() as f: 950 ... f.readline() 951 ... 952 '#!/usr/bin/env python3\n' 953 954 955.. method:: Path.owner() 956 957 Return the name of the user owning the file. :exc:`KeyError` is raised 958 if the file's uid isn't found in the system database. 959 960 961.. method:: Path.read_bytes() 962 963 Return the binary contents of the pointed-to file as a bytes object:: 964 965 >>> p = Path('my_binary_file') 966 >>> p.write_bytes(b'Binary file contents') 967 20 968 >>> p.read_bytes() 969 b'Binary file contents' 970 971 .. versionadded:: 3.5 972 973 974.. method:: Path.read_text(encoding=None, errors=None) 975 976 Return the decoded contents of the pointed-to file as a string:: 977 978 >>> p = Path('my_text_file') 979 >>> p.write_text('Text file contents') 980 18 981 >>> p.read_text() 982 'Text file contents' 983 984 The file is opened and then closed. The optional parameters have the same 985 meaning as in :func:`open`. 986 987 .. versionadded:: 3.5 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 1003.. method:: Path.rename(target) 1004 1005 Rename this file or directory to the given *target*, and return a new Path 1006 instance pointing to *target*. On Unix, if *target* exists and is a file, 1007 it will be replaced silently if the user has permission. *target* can be 1008 either a string or another path object:: 1009 1010 >>> p = Path('foo') 1011 >>> p.open('w').write('some text') 1012 9 1013 >>> target = Path('bar') 1014 >>> p.rename(target) 1015 PosixPath('bar') 1016 >>> target.open().read() 1017 'some text' 1018 1019 The target path may be absolute or relative. Relative paths are interpreted 1020 relative to the current working directory, *not* the directory of the Path 1021 object. 1022 1023 .. versionchanged:: 3.8 1024 Added return value, return the new Path instance. 1025 1026 1027.. method:: Path.replace(target) 1028 1029 Rename this file or directory to the given *target*, and return a new Path 1030 instance pointing to *target*. If *target* points to an existing file or 1031 directory, it will be unconditionally replaced. 1032 1033 The target path may be absolute or relative. Relative paths are interpreted 1034 relative to the current working directory, *not* the directory of the Path 1035 object. 1036 1037 .. versionchanged:: 3.8 1038 Added return value, return the new Path instance. 1039 1040 1041.. method:: Path.resolve(strict=False) 1042 1043 Make the path absolute, resolving any symlinks. A new path object is 1044 returned:: 1045 1046 >>> p = Path() 1047 >>> p 1048 PosixPath('.') 1049 >>> p.resolve() 1050 PosixPath('/home/antoine/pathlib') 1051 1052 "``..``" components are also eliminated (this is the only method to do so):: 1053 1054 >>> p = Path('docs/../setup.py') 1055 >>> p.resolve() 1056 PosixPath('/home/antoine/pathlib/setup.py') 1057 1058 If the path doesn't exist and *strict* is ``True``, :exc:`FileNotFoundError` 1059 is raised. If *strict* is ``False``, the path is resolved as far as possible 1060 and any remainder is appended without checking whether it exists. If an 1061 infinite loop is encountered along the resolution path, :exc:`RuntimeError` 1062 is raised. 1063 1064 .. versionadded:: 3.6 1065 The *strict* argument (pre-3.6 behavior is strict). 1066 1067.. method:: Path.rglob(pattern) 1068 1069 This is like calling :func:`Path.glob` with "``**/``" added in front of the 1070 given relative *pattern*:: 1071 1072 >>> sorted(Path().rglob("*.py")) 1073 [PosixPath('build/lib/pathlib.py'), 1074 PosixPath('docs/conf.py'), 1075 PosixPath('pathlib.py'), 1076 PosixPath('setup.py'), 1077 PosixPath('test_pathlib.py')] 1078 1079 .. audit-event:: pathlib.Path.rglob self,pattern pathlib.Path.rglob 1080 1081 1082.. method:: Path.rmdir() 1083 1084 Remove this directory. The directory must be empty. 1085 1086 1087.. method:: Path.samefile(other_path) 1088 1089 Return whether this path points to the same file as *other_path*, which 1090 can be either a Path object, or a string. The semantics are similar 1091 to :func:`os.path.samefile` and :func:`os.path.samestat`. 1092 1093 An :exc:`OSError` can be raised if either file cannot be accessed for some 1094 reason. 1095 1096 :: 1097 1098 >>> p = Path('spam') 1099 >>> q = Path('eggs') 1100 >>> p.samefile(q) 1101 False 1102 >>> p.samefile('spam') 1103 True 1104 1105 .. versionadded:: 3.5 1106 1107 1108.. method:: Path.symlink_to(target, target_is_directory=False) 1109 1110 Make this path a symbolic link to *target*. Under Windows, 1111 *target_is_directory* must be true (default ``False``) if the link's target 1112 is a directory. Under POSIX, *target_is_directory*'s value is ignored. 1113 1114 :: 1115 1116 >>> p = Path('mylink') 1117 >>> p.symlink_to('setup.py') 1118 >>> p.resolve() 1119 PosixPath('/home/antoine/pathlib/setup.py') 1120 >>> p.stat().st_size 1121 956 1122 >>> p.lstat().st_size 1123 8 1124 1125 .. note:: 1126 The order of arguments (link, target) is the reverse 1127 of :func:`os.symlink`'s. 1128 1129 1130.. method:: Path.link_to(target) 1131 1132 Make *target* a hard link to this path. 1133 1134 .. warning:: 1135 1136 This function does not make this path a hard link to *target*, despite 1137 the implication of the function and argument names. The argument order 1138 (target, link) is the reverse of :func:`Path.symlink_to`, but matches 1139 that of :func:`os.link`. 1140 1141 .. versionadded:: 3.8 1142 1143 1144.. method:: Path.touch(mode=0o666, exist_ok=True) 1145 1146 Create a file at this given path. If *mode* is given, it is combined 1147 with the process' ``umask`` value to determine the file mode and access 1148 flags. If the file already exists, the function succeeds if *exist_ok* 1149 is true (and its modification time is updated to the current time), 1150 otherwise :exc:`FileExistsError` is raised. 1151 1152 1153.. method:: Path.unlink(missing_ok=False) 1154 1155 Remove this file or symbolic link. If the path points to a directory, 1156 use :func:`Path.rmdir` instead. 1157 1158 If *missing_ok* is false (the default), :exc:`FileNotFoundError` is 1159 raised if the path does not exist. 1160 1161 If *missing_ok* is true, :exc:`FileNotFoundError` exceptions will be 1162 ignored (same behavior as the POSIX ``rm -f`` command). 1163 1164 .. versionchanged:: 3.8 1165 The *missing_ok* parameter was added. 1166 1167 1168.. method:: Path.write_bytes(data) 1169 1170 Open the file pointed to in bytes mode, write *data* to it, and close the 1171 file:: 1172 1173 >>> p = Path('my_binary_file') 1174 >>> p.write_bytes(b'Binary file contents') 1175 20 1176 >>> p.read_bytes() 1177 b'Binary file contents' 1178 1179 An existing file of the same name is overwritten. 1180 1181 .. versionadded:: 3.5 1182 1183 1184.. method:: Path.write_text(data, encoding=None, errors=None) 1185 1186 Open the file pointed to in text mode, write *data* to it, and close the 1187 file:: 1188 1189 >>> p = Path('my_text_file') 1190 >>> p.write_text('Text file contents') 1191 18 1192 >>> p.read_text() 1193 'Text file contents' 1194 1195 An existing file of the same name is overwritten. The optional parameters 1196 have the same meaning as in :func:`open`. 1197 1198 .. versionadded:: 3.5 1199 1200Correspondence to tools in the :mod:`os` module 1201----------------------------------------------- 1202 1203Below is a table mapping various :mod:`os` functions to their corresponding 1204:class:`PurePath`/:class:`Path` equivalent. 1205 1206.. note:: 1207 1208 Although :func:`os.path.relpath` and :meth:`PurePath.relative_to` have some 1209 overlapping use-cases, their semantics differ enough to warrant not 1210 considering them equivalent. 1211 1212==================================== ============================== 1213os and os.path pathlib 1214==================================== ============================== 1215:func:`os.path.abspath` :meth:`Path.resolve` 1216:func:`os.chmod` :meth:`Path.chmod` 1217:func:`os.mkdir` :meth:`Path.mkdir` 1218:func:`os.makedirs` :meth:`Path.mkdir` 1219:func:`os.rename` :meth:`Path.rename` 1220:func:`os.replace` :meth:`Path.replace` 1221:func:`os.rmdir` :meth:`Path.rmdir` 1222:func:`os.remove`, :func:`os.unlink` :meth:`Path.unlink` 1223:func:`os.getcwd` :func:`Path.cwd` 1224:func:`os.path.exists` :meth:`Path.exists` 1225:func:`os.path.expanduser` :meth:`Path.expanduser` and 1226 :meth:`Path.home` 1227:func:`os.listdir` :meth:`Path.iterdir` 1228:func:`os.path.isdir` :meth:`Path.is_dir` 1229:func:`os.path.isfile` :meth:`Path.is_file` 1230:func:`os.path.islink` :meth:`Path.is_symlink` 1231:func:`os.link` :meth:`Path.link_to` 1232:func:`os.symlink` :meth:`Path.symlink_to` 1233:func:`os.readlink` :meth:`Path.readlink` 1234:func:`os.stat` :meth:`Path.stat`, 1235 :meth:`Path.owner`, 1236 :meth:`Path.group` 1237:func:`os.path.isabs` :meth:`PurePath.is_absolute` 1238:func:`os.path.join` :func:`PurePath.joinpath` 1239:func:`os.path.basename` :data:`PurePath.name` 1240:func:`os.path.dirname` :data:`PurePath.parent` 1241:func:`os.path.samefile` :meth:`Path.samefile` 1242:func:`os.path.splitext` :data:`PurePath.suffix` 1243==================================== ============================== 1244