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