• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
15This module offers classes representing filesystem paths with semantics
16appropriate for different operating systems.  Path classes are divided
17between :ref:`pure paths <pure-paths>`, which provide purely computational
18operations without I/O, and :ref:`concrete paths <concrete-paths>`, which
19inherit 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
31If you've never used this module before or just aren't sure which class is
32right for your task, :class:`Path` is most likely what you need. It instantiates
33a :ref:`concrete path <concrete-paths>` for the platform the code is running on.
34
35Pure 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
52Basic use
53---------
54
55Importing the main class::
56
57   >>> from pathlib import Path
58
59Listing 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
66Listing 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
73Navigating 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
82Querying path properties::
83
84   >>> q.exists()
85   True
86   >>> q.is_dir()
87   False
88
89Opening a file::
90
91   >>> with q.open() as f: f.readline()
92   ...
93   '#!/bin/bash\n'
94
95
96Exceptions
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
109Pure paths
110----------
111
112Pure path objects provide path-handling operations which don't actually
113access a filesystem.  There are three ways to access these classes, which
114we 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
200Regardless of the system you're running on, you can instantiate all of
201these classes, since they don't provide any operation that does system calls.
202
203
204General properties
205^^^^^^^^^^^^^^^^^^
206
207Paths are immutable and :term:`hashable`.  Paths of a same flavour are comparable
208and orderable.  These properties respect the flavour's case-folding
209semantics::
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
220Paths 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
230Operators
231^^^^^^^^^
232
233The slash operator helps create child paths, like :func:`os.path.join`.
234If the argument is an absolute path, the previous path is ignored.
235On Windows, the drive is not reset when the argument is a rooted
236relative 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
251A path object can be used anywhere an object implementing :class:`os.PathLike`
252is accepted::
253
254   >>> import os
255   >>> p = PurePath('/etc')
256   >>> os.fspath(p)
257   '/etc'
258
259The string representation of a path is the raw filesystem path itself
260(in native form, e.g. with backslashes under Windows), which you can
261pass 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
270Similarly, calling :class:`bytes` on a path gives the raw filesystem path as a
271bytes 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
281Accessing individual parts
282^^^^^^^^^^^^^^^^^^^^^^^^^^
283
284To access the individual "parts" (components) of a path, use the following
285property:
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
302Methods and properties
303^^^^^^^^^^^^^^^^^^^^^^
304
305.. testsetup::
306
307   from pathlib import PurePath, PurePosixPath, PureWindowsPath
308
309Pure 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.. attribute:: PurePath.suffixes
459
460   A list of the path's suffixes, often called file extensions::
461
462      >>> PurePosixPath('my/library.tar.gar').suffixes
463      ['.tar', '.gar']
464      >>> PurePosixPath('my/library.tar.gz').suffixes
465      ['.tar', '.gz']
466      >>> PurePosixPath('my/library').suffixes
467      []
468
469
470.. attribute:: PurePath.stem
471
472   The final path component, without its suffix::
473
474      >>> PurePosixPath('my/library.tar.gz').stem
475      'library.tar'
476      >>> PurePosixPath('my/library.tar').stem
477      'library'
478      >>> PurePosixPath('my/library').stem
479      'library'
480
481
482.. method:: PurePath.as_posix()
483
484   Return a string representation of the path with forward slashes (``/``)::
485
486      >>> p = PureWindowsPath('c:\\windows')
487      >>> str(p)
488      'c:\\windows'
489      >>> p.as_posix()
490      'c:/windows'
491
492
493.. method:: PurePath.is_absolute()
494
495   Return whether the path is absolute or not.  A path is considered absolute
496   if it has both a root and (if the flavour allows) a drive::
497
498      >>> PurePosixPath('/a/b').is_absolute()
499      True
500      >>> PurePosixPath('a/b').is_absolute()
501      False
502
503      >>> PureWindowsPath('c:/a/b').is_absolute()
504      True
505      >>> PureWindowsPath('/a/b').is_absolute()
506      False
507      >>> PureWindowsPath('c:').is_absolute()
508      False
509      >>> PureWindowsPath('//some/share').is_absolute()
510      True
511
512
513.. method:: PurePath.is_relative_to(other)
514
515   Return whether or not this path is relative to the *other* path.
516
517      >>> p = PurePath('/etc/passwd')
518      >>> p.is_relative_to('/etc')
519      True
520      >>> p.is_relative_to('/usr')
521      False
522
523   This method is string-based; it neither accesses the filesystem nor treats
524   "``..``" segments specially. The following code is equivalent:
525
526      >>> u = PurePath('/usr')
527      >>> u == p or u in p.parents
528      False
529
530   .. versionadded:: 3.9
531
532   .. deprecated-removed:: 3.12 3.14
533
534      Passing additional arguments is deprecated; if supplied, they are joined
535      with *other*.
536
537.. method:: PurePath.is_reserved()
538
539   With :class:`PureWindowsPath`, return ``True`` if the path is considered
540   reserved under Windows, ``False`` otherwise.  With :class:`PurePosixPath`,
541   ``False`` is always returned.
542
543   .. versionchanged:: 3.13
544      Windows path names that contain a colon, or end with a dot or a space,
545      are considered reserved. UNC paths may be reserved.
546
547   .. deprecated-removed:: 3.13 3.15
548      This method is deprecated; use :func:`os.path.isreserved` to detect
549      reserved paths on Windows.
550
551.. method:: PurePath.joinpath(*pathsegments)
552
553   Calling this method is equivalent to combining the path with each of
554   the given *pathsegments* in turn::
555
556      >>> PurePosixPath('/etc').joinpath('passwd')
557      PurePosixPath('/etc/passwd')
558      >>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
559      PurePosixPath('/etc/passwd')
560      >>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
561      PurePosixPath('/etc/init.d/apache2')
562      >>> PureWindowsPath('c:').joinpath('/Program Files')
563      PureWindowsPath('c:/Program Files')
564
565
566.. method:: PurePath.full_match(pattern, *, case_sensitive=None)
567
568   Match this path against the provided glob-style pattern.  Return ``True``
569   if matching is successful, ``False`` otherwise.  For example::
570
571      >>> PurePath('a/b.py').full_match('a/*.py')
572      True
573      >>> PurePath('a/b.py').full_match('*.py')
574      False
575      >>> PurePath('/a/b/c.py').full_match('/a/**')
576      True
577      >>> PurePath('/a/b/c.py').full_match('**/*.py')
578      True
579
580   .. seealso::
581      :ref:`pathlib-pattern-language` documentation.
582
583   As with other methods, case-sensitivity follows platform defaults::
584
585      >>> PurePosixPath('b.py').full_match('*.PY')
586      False
587      >>> PureWindowsPath('b.py').full_match('*.PY')
588      True
589
590   Set *case_sensitive* to ``True`` or ``False`` to override this behaviour.
591
592   .. versionadded:: 3.13
593
594
595.. method:: PurePath.match(pattern, *, case_sensitive=None)
596
597   Match this path against the provided non-recursive glob-style pattern.
598   Return ``True`` if matching is successful, ``False`` otherwise.
599
600   This method is similar to :meth:`~PurePath.full_match`, but empty patterns
601   aren't allowed (:exc:`ValueError` is raised), the recursive wildcard
602   "``**``" isn't supported (it acts like non-recursive "``*``"), and if a
603   relative pattern is provided, then matching is done from the right::
604
605      >>> PurePath('a/b.py').match('*.py')
606      True
607      >>> PurePath('/a/b/c.py').match('b/*.py')
608      True
609      >>> PurePath('/a/b/c.py').match('a/*.py')
610      False
611
612   .. versionchanged:: 3.12
613      The *pattern* parameter accepts a :term:`path-like object`.
614
615   .. versionchanged:: 3.12
616      The *case_sensitive* parameter was added.
617
618
619.. method:: PurePath.relative_to(other, walk_up=False)
620
621   Compute a version of this path relative to the path represented by
622   *other*.  If it's impossible, :exc:`ValueError` is raised::
623
624      >>> p = PurePosixPath('/etc/passwd')
625      >>> p.relative_to('/')
626      PurePosixPath('etc/passwd')
627      >>> p.relative_to('/etc')
628      PurePosixPath('passwd')
629      >>> p.relative_to('/usr')
630      Traceback (most recent call last):
631        File "<stdin>", line 1, in <module>
632        File "pathlib.py", line 941, in relative_to
633          raise ValueError(error_message.format(str(self), str(formatted)))
634      ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other is absolute.
635
636   When *walk_up* is false (the default), the path must start with *other*.
637   When the argument is true, ``..`` entries may be added to form the
638   relative path. In all other cases, such as the paths referencing
639   different drives, :exc:`ValueError` is raised.::
640
641      >>> p.relative_to('/usr', walk_up=True)
642      PurePosixPath('../etc/passwd')
643      >>> p.relative_to('foo', walk_up=True)
644      Traceback (most recent call last):
645        File "<stdin>", line 1, in <module>
646        File "pathlib.py", line 941, in relative_to
647          raise ValueError(error_message.format(str(self), str(formatted)))
648      ValueError: '/etc/passwd' is not on the same drive as 'foo' OR one path is relative and the other is absolute.
649
650   .. warning::
651      This function is part of :class:`PurePath` and works with strings.
652      It does not check or access the underlying file structure.
653      This can impact the *walk_up* option as it assumes that no symlinks
654      are present in the path; call :meth:`~Path.resolve` first if
655      necessary to resolve symlinks.
656
657   .. versionchanged:: 3.12
658      The *walk_up* parameter was added (old behavior is the same as ``walk_up=False``).
659
660   .. deprecated-removed:: 3.12 3.14
661
662      Passing additional positional arguments is deprecated; if supplied,
663      they are joined with *other*.
664
665.. method:: PurePath.with_name(name)
666
667   Return a new path with the :attr:`name` changed.  If the original path
668   doesn't have a name, ValueError is raised::
669
670      >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
671      >>> p.with_name('setup.py')
672      PureWindowsPath('c:/Downloads/setup.py')
673      >>> p = PureWindowsPath('c:/')
674      >>> p.with_name('setup.py')
675      Traceback (most recent call last):
676        File "<stdin>", line 1, in <module>
677        File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
678          raise ValueError("%r has an empty name" % (self,))
679      ValueError: PureWindowsPath('c:/') has an empty name
680
681
682.. method:: PurePath.with_stem(stem)
683
684   Return a new path with the :attr:`stem` changed.  If the original path
685   doesn't have a name, ValueError is raised::
686
687      >>> p = PureWindowsPath('c:/Downloads/draft.txt')
688      >>> p.with_stem('final')
689      PureWindowsPath('c:/Downloads/final.txt')
690      >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
691      >>> p.with_stem('lib')
692      PureWindowsPath('c:/Downloads/lib.gz')
693      >>> p = PureWindowsPath('c:/')
694      >>> p.with_stem('')
695      Traceback (most recent call last):
696        File "<stdin>", line 1, in <module>
697        File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem
698          return self.with_name(stem + self.suffix)
699        File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name
700          raise ValueError("%r has an empty name" % (self,))
701      ValueError: PureWindowsPath('c:/') has an empty name
702
703   .. versionadded:: 3.9
704
705
706.. method:: PurePath.with_suffix(suffix)
707
708   Return a new path with the :attr:`suffix` changed.  If the original path
709   doesn't have a suffix, the new *suffix* is appended instead.  If the
710   *suffix* is an empty string, the original suffix is removed::
711
712      >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
713      >>> p.with_suffix('.bz2')
714      PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
715      >>> p = PureWindowsPath('README')
716      >>> p.with_suffix('.txt')
717      PureWindowsPath('README.txt')
718      >>> p = PureWindowsPath('README.txt')
719      >>> p.with_suffix('')
720      PureWindowsPath('README')
721
722
723.. method:: PurePath.with_segments(*pathsegments)
724
725   Create a new path object of the same type by combining the given
726   *pathsegments*. This method is called whenever a derivative path is created,
727   such as from :attr:`parent` and :meth:`relative_to`. Subclasses may
728   override this method to pass information to derivative paths, for example::
729
730      from pathlib import PurePosixPath
731
732      class MyPath(PurePosixPath):
733          def __init__(self, *pathsegments, session_id):
734              super().__init__(*pathsegments)
735              self.session_id = session_id
736
737          def with_segments(self, *pathsegments):
738              return type(self)(*pathsegments, session_id=self.session_id)
739
740      etc = MyPath('/etc', session_id=42)
741      hosts = etc / 'hosts'
742      print(hosts.session_id)  # 42
743
744   .. versionadded:: 3.12
745
746
747.. _concrete-paths:
748
749
750Concrete paths
751--------------
752
753Concrete paths are subclasses of the pure path classes.  In addition to
754operations provided by the latter, they also provide methods to do system
755calls on path objects.  There are three ways to instantiate concrete paths:
756
757.. class:: Path(*pathsegments)
758
759   A subclass of :class:`PurePath`, this class represents concrete paths of
760   the system's path flavour (instantiating it creates either a
761   :class:`PosixPath` or a :class:`WindowsPath`)::
762
763      >>> Path('setup.py')
764      PosixPath('setup.py')
765
766   *pathsegments* is specified similarly to :class:`PurePath`.
767
768.. class:: PosixPath(*pathsegments)
769
770   A subclass of :class:`Path` and :class:`PurePosixPath`, this class
771   represents concrete non-Windows filesystem paths::
772
773      >>> PosixPath('/etc/hosts')
774      PosixPath('/etc/hosts')
775
776   *pathsegments* is specified similarly to :class:`PurePath`.
777
778   .. versionchanged:: 3.13
779      Raises :exc:`UnsupportedOperation` on Windows. In previous versions,
780      :exc:`NotImplementedError` was raised instead.
781
782
783.. class:: WindowsPath(*pathsegments)
784
785   A subclass of :class:`Path` and :class:`PureWindowsPath`, this class
786   represents concrete Windows filesystem paths::
787
788      >>> WindowsPath('c:/', 'Users', 'Ximénez')
789      WindowsPath('c:/Users/Ximénez')
790
791   *pathsegments* is specified similarly to :class:`PurePath`.
792
793   .. versionchanged:: 3.13
794      Raises :exc:`UnsupportedOperation` on non-Windows platforms. In previous
795      versions, :exc:`NotImplementedError` was raised instead.
796
797
798You can only instantiate the class flavour that corresponds to your system
799(allowing system calls on non-compatible path flavours could lead to
800bugs or failures in your application)::
801
802   >>> import os
803   >>> os.name
804   'posix'
805   >>> Path('setup.py')
806   PosixPath('setup.py')
807   >>> PosixPath('setup.py')
808   PosixPath('setup.py')
809   >>> WindowsPath('setup.py')
810   Traceback (most recent call last):
811     File "<stdin>", line 1, in <module>
812     File "pathlib.py", line 798, in __new__
813       % (cls.__name__,))
814   UnsupportedOperation: cannot instantiate 'WindowsPath' on your system
815
816Some concrete path methods can raise an :exc:`OSError` if a system call fails
817(for example because the path doesn't exist).
818
819
820Parsing and generating URIs
821^^^^^^^^^^^^^^^^^^^^^^^^^^^
822
823Concrete path objects can be created from, and represented as, 'file' URIs
824conforming to :rfc:`8089`.
825
826.. note::
827
828   File URIs are not portable across machines with different
829   :ref:`filesystem encodings <filesystem-encoding>`.
830
831.. classmethod:: Path.from_uri(uri)
832
833   Return a new path object from parsing a 'file' URI. For example::
834
835      >>> p = Path.from_uri('file:///etc/hosts')
836      PosixPath('/etc/hosts')
837
838   On Windows, DOS device and UNC paths may be parsed from URIs::
839
840      >>> p = Path.from_uri('file:///c:/windows')
841      WindowsPath('c:/windows')
842      >>> p = Path.from_uri('file://server/share')
843      WindowsPath('//server/share')
844
845   Several variant forms are supported::
846
847      >>> p = Path.from_uri('file:////server/share')
848      WindowsPath('//server/share')
849      >>> p = Path.from_uri('file://///server/share')
850      WindowsPath('//server/share')
851      >>> p = Path.from_uri('file:c:/windows')
852      WindowsPath('c:/windows')
853      >>> p = Path.from_uri('file:/c|/windows')
854      WindowsPath('c:/windows')
855
856   :exc:`ValueError` is raised if the URI does not start with ``file:``, or
857   the parsed path isn't absolute.
858
859   .. versionadded:: 3.13
860
861
862.. method:: Path.as_uri()
863
864   Represent the path as a 'file' URI.  :exc:`ValueError` is raised if
865   the path isn't absolute.
866
867   .. code-block:: pycon
868
869      >>> p = PosixPath('/etc/passwd')
870      >>> p.as_uri()
871      'file:///etc/passwd'
872      >>> p = WindowsPath('c:/Windows')
873      >>> p.as_uri()
874      'file:///c:/Windows'
875
876   For historical reasons, this method is also available from
877   :class:`PurePath` objects. However, its use of :func:`os.fsencode` makes
878   it strictly impure.
879
880
881Expanding and resolving paths
882^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
883
884.. classmethod:: Path.home()
885
886   Return a new path object representing the user's home directory (as
887   returned by :func:`os.path.expanduser` with ``~`` construct). If the home
888   directory can't be resolved, :exc:`RuntimeError` is raised.
889
890   ::
891
892      >>> Path.home()
893      PosixPath('/home/antoine')
894
895   .. versionadded:: 3.5
896
897
898.. method:: Path.expanduser()
899
900   Return a new path with expanded ``~`` and ``~user`` constructs,
901   as returned by :meth:`os.path.expanduser`. If a home directory can't be
902   resolved, :exc:`RuntimeError` is raised.
903
904   ::
905
906      >>> p = PosixPath('~/films/Monty Python')
907      >>> p.expanduser()
908      PosixPath('/home/eric/films/Monty Python')
909
910   .. versionadded:: 3.5
911
912
913.. classmethod:: Path.cwd()
914
915   Return a new path object representing the current directory (as returned
916   by :func:`os.getcwd`)::
917
918      >>> Path.cwd()
919      PosixPath('/home/antoine/pathlib')
920
921
922.. method:: Path.absolute()
923
924   Make the path absolute, without normalization or resolving symlinks.
925   Returns a new path object::
926
927      >>> p = Path('tests')
928      >>> p
929      PosixPath('tests')
930      >>> p.absolute()
931      PosixPath('/home/antoine/pathlib/tests')
932
933
934.. method:: Path.resolve(strict=False)
935
936   Make the path absolute, resolving any symlinks.  A new path object is
937   returned::
938
939      >>> p = Path()
940      >>> p
941      PosixPath('.')
942      >>> p.resolve()
943      PosixPath('/home/antoine/pathlib')
944
945   "``..``" components are also eliminated (this is the only method to do so)::
946
947      >>> p = Path('docs/../setup.py')
948      >>> p.resolve()
949      PosixPath('/home/antoine/pathlib/setup.py')
950
951   If a path doesn't exist or a symlink loop is encountered, and *strict* is
952   ``True``, :exc:`OSError` is raised.  If *strict* is ``False``, the path is
953   resolved as far as possible and any remainder is appended without checking
954   whether it exists.
955
956   .. versionchanged:: 3.6
957      The *strict* parameter was added (pre-3.6 behavior is strict).
958
959   .. versionchanged:: 3.13
960      Symlink loops are treated like other errors: :exc:`OSError` is raised in
961      strict mode, and no exception is raised in non-strict mode. In previous
962      versions, :exc:`RuntimeError` is raised no matter the value of *strict*.
963
964
965.. method:: Path.readlink()
966
967   Return the path to which the symbolic link points (as returned by
968   :func:`os.readlink`)::
969
970      >>> p = Path('mylink')
971      >>> p.symlink_to('setup.py')
972      >>> p.readlink()
973      PosixPath('setup.py')
974
975   .. versionadded:: 3.9
976
977   .. versionchanged:: 3.13
978      Raises :exc:`UnsupportedOperation` if :func:`os.readlink` is not
979      available. In previous versions, :exc:`NotImplementedError` was raised.
980
981
982Querying file type and status
983^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
984
985.. versionchanged:: 3.8
986
987   :meth:`~Path.exists`, :meth:`~Path.is_dir`, :meth:`~Path.is_file`,
988   :meth:`~Path.is_mount`, :meth:`~Path.is_symlink`,
989   :meth:`~Path.is_block_device`, :meth:`~Path.is_char_device`,
990   :meth:`~Path.is_fifo`, :meth:`~Path.is_socket` now return ``False``
991   instead of raising an exception for paths that contain characters
992   unrepresentable at the OS level.
993
994
995.. method:: Path.stat(*, follow_symlinks=True)
996
997   Return an :class:`os.stat_result` object containing information about this path, like :func:`os.stat`.
998   The result is looked up at each call to this method.
999
1000   This method normally follows symlinks; to stat a symlink add the argument
1001   ``follow_symlinks=False``, or use :meth:`~Path.lstat`.
1002
1003   ::
1004
1005      >>> p = Path('setup.py')
1006      >>> p.stat().st_size
1007      956
1008      >>> p.stat().st_mtime
1009      1327883547.852554
1010
1011   .. versionchanged:: 3.10
1012      The *follow_symlinks* parameter was added.
1013
1014
1015.. method:: Path.lstat()
1016
1017   Like :meth:`Path.stat` but, if the path points to a symbolic link, return
1018   the symbolic link's information rather than its target's.
1019
1020
1021.. method:: Path.exists(*, follow_symlinks=True)
1022
1023   Return ``True`` if the path points to an existing file or directory.
1024
1025   This method normally follows symlinks; to check if a symlink exists, add
1026   the argument ``follow_symlinks=False``.
1027
1028   ::
1029
1030      >>> Path('.').exists()
1031      True
1032      >>> Path('setup.py').exists()
1033      True
1034      >>> Path('/etc').exists()
1035      True
1036      >>> Path('nonexistentfile').exists()
1037      False
1038
1039   .. versionchanged:: 3.12
1040      The *follow_symlinks* parameter was added.
1041
1042
1043.. method:: Path.is_file(*, follow_symlinks=True)
1044
1045   Return ``True`` if the path points to a regular file, ``False`` if it
1046   points to another kind of file.
1047
1048   ``False`` is also returned if the path doesn't exist or is a broken symlink;
1049   other errors (such as permission errors) are propagated.
1050
1051   This method normally follows symlinks; to exclude symlinks, add the
1052   argument ``follow_symlinks=False``.
1053
1054   .. versionchanged:: 3.13
1055      The *follow_symlinks* parameter was added.
1056
1057
1058.. method:: Path.is_dir(*, follow_symlinks=True)
1059
1060   Return ``True`` if the path points to a directory, ``False`` if it points
1061   to another kind of file.
1062
1063   ``False`` is also returned if the path doesn't exist or is a broken symlink;
1064   other errors (such as permission errors) are propagated.
1065
1066   This method normally follows symlinks; to exclude symlinks to directories,
1067   add the argument ``follow_symlinks=False``.
1068
1069   .. versionchanged:: 3.13
1070      The *follow_symlinks* parameter was added.
1071
1072
1073.. method:: Path.is_symlink()
1074
1075   Return ``True`` if the path points to a symbolic link, ``False`` otherwise.
1076
1077   ``False`` is also returned if the path doesn't exist; other errors (such
1078   as permission errors) are propagated.
1079
1080
1081.. method:: Path.is_junction()
1082
1083   Return ``True`` if the path points to a junction, and ``False`` for any other
1084   type of file. Currently only Windows supports junctions.
1085
1086   .. versionadded:: 3.12
1087
1088
1089.. method:: Path.is_mount()
1090
1091   Return ``True`` if the path is a :dfn:`mount point`: a point in a
1092   file system where a different file system has been mounted.  On POSIX, the
1093   function checks whether *path*'s parent, :file:`path/..`, is on a different
1094   device than *path*, or whether :file:`path/..` and *path* point to the same
1095   i-node on the same device --- this should detect mount points for all Unix
1096   and POSIX variants.  On Windows, a mount point is considered to be a drive
1097   letter root (e.g. ``c:\``), a UNC share (e.g. ``\\server\share``), or a
1098   mounted filesystem directory.
1099
1100   .. versionadded:: 3.7
1101
1102   .. versionchanged:: 3.12
1103      Windows support was added.
1104
1105
1106.. method:: Path.is_socket()
1107
1108   Return ``True`` if the path points to a Unix socket (or a symbolic link
1109   pointing to a Unix socket), ``False`` if it points to another kind of file.
1110
1111   ``False`` is also returned if the path doesn't exist or is a broken symlink;
1112   other errors (such as permission errors) are propagated.
1113
1114
1115.. method:: Path.is_fifo()
1116
1117   Return ``True`` if the path points to a FIFO (or a symbolic link
1118   pointing to a FIFO), ``False`` if it points to another kind of file.
1119
1120   ``False`` is also returned if the path doesn't exist or is a broken symlink;
1121   other errors (such as permission errors) are propagated.
1122
1123
1124.. method:: Path.is_block_device()
1125
1126   Return ``True`` if the path points to a block device (or a symbolic link
1127   pointing to a block device), ``False`` if it points to another kind of file.
1128
1129   ``False`` is also returned if the path doesn't exist or is a broken symlink;
1130   other errors (such as permission errors) are propagated.
1131
1132
1133.. method:: Path.is_char_device()
1134
1135   Return ``True`` if the path points to a character device (or a symbolic link
1136   pointing to a character device), ``False`` if it points to another kind of file.
1137
1138   ``False`` is also returned if the path doesn't exist or is a broken symlink;
1139   other errors (such as permission errors) are propagated.
1140
1141
1142.. method:: Path.samefile(other_path)
1143
1144   Return whether this path points to the same file as *other_path*, which
1145   can be either a Path object, or a string.  The semantics are similar
1146   to :func:`os.path.samefile` and :func:`os.path.samestat`.
1147
1148   An :exc:`OSError` can be raised if either file cannot be accessed for some
1149   reason.
1150
1151   ::
1152
1153      >>> p = Path('spam')
1154      >>> q = Path('eggs')
1155      >>> p.samefile(q)
1156      False
1157      >>> p.samefile('spam')
1158      True
1159
1160   .. versionadded:: 3.5
1161
1162
1163Reading and writing files
1164^^^^^^^^^^^^^^^^^^^^^^^^^
1165
1166
1167.. method:: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
1168
1169   Open the file pointed to by the path, like the built-in :func:`open`
1170   function does::
1171
1172      >>> p = Path('setup.py')
1173      >>> with p.open() as f:
1174      ...     f.readline()
1175      ...
1176      '#!/usr/bin/env python3\n'
1177
1178
1179.. method:: Path.read_text(encoding=None, errors=None, newline=None)
1180
1181   Return the decoded contents of the pointed-to file as a string::
1182
1183      >>> p = Path('my_text_file')
1184      >>> p.write_text('Text file contents')
1185      18
1186      >>> p.read_text()
1187      'Text file contents'
1188
1189   The file is opened and then closed. The optional parameters have the same
1190   meaning as in :func:`open`.
1191
1192   .. versionadded:: 3.5
1193
1194   .. versionchanged:: 3.13
1195      The *newline* parameter was added.
1196
1197
1198.. method:: Path.read_bytes()
1199
1200   Return the binary contents of the pointed-to file as a bytes object::
1201
1202      >>> p = Path('my_binary_file')
1203      >>> p.write_bytes(b'Binary file contents')
1204      20
1205      >>> p.read_bytes()
1206      b'Binary file contents'
1207
1208   .. versionadded:: 3.5
1209
1210
1211.. method:: Path.write_text(data, encoding=None, errors=None, newline=None)
1212
1213   Open the file pointed to in text mode, write *data* to it, and close the
1214   file::
1215
1216      >>> p = Path('my_text_file')
1217      >>> p.write_text('Text file contents')
1218      18
1219      >>> p.read_text()
1220      'Text file contents'
1221
1222   An existing file of the same name is overwritten. The optional parameters
1223   have the same meaning as in :func:`open`.
1224
1225   .. versionadded:: 3.5
1226
1227   .. versionchanged:: 3.10
1228      The *newline* parameter was added.
1229
1230
1231.. method:: Path.write_bytes(data)
1232
1233   Open the file pointed to in bytes mode, write *data* to it, and close the
1234   file::
1235
1236      >>> p = Path('my_binary_file')
1237      >>> p.write_bytes(b'Binary file contents')
1238      20
1239      >>> p.read_bytes()
1240      b'Binary file contents'
1241
1242   An existing file of the same name is overwritten.
1243
1244   .. versionadded:: 3.5
1245
1246
1247Reading directories
1248^^^^^^^^^^^^^^^^^^^
1249
1250.. method:: Path.iterdir()
1251
1252   When the path points to a directory, yield path objects of the directory
1253   contents::
1254
1255      >>> p = Path('docs')
1256      >>> for child in p.iterdir(): child
1257      ...
1258      PosixPath('docs/conf.py')
1259      PosixPath('docs/_templates')
1260      PosixPath('docs/make.bat')
1261      PosixPath('docs/index.rst')
1262      PosixPath('docs/_build')
1263      PosixPath('docs/_static')
1264      PosixPath('docs/Makefile')
1265
1266   The children are yielded in arbitrary order, and the special entries
1267   ``'.'`` and ``'..'`` are not included.  If a file is removed from or added
1268   to the directory after creating the iterator, it is unspecified whether
1269   a path object for that file is included.
1270
1271   If the path is not a directory or otherwise inaccessible, :exc:`OSError` is
1272   raised.
1273
1274.. method:: Path.glob(pattern, *, case_sensitive=None, recurse_symlinks=False)
1275
1276   Glob the given relative *pattern* in the directory represented by this path,
1277   yielding all matching files (of any kind)::
1278
1279      >>> sorted(Path('.').glob('*.py'))
1280      [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
1281      >>> sorted(Path('.').glob('*/*.py'))
1282      [PosixPath('docs/conf.py')]
1283      >>> sorted(Path('.').glob('**/*.py'))
1284      [PosixPath('build/lib/pathlib.py'),
1285       PosixPath('docs/conf.py'),
1286       PosixPath('pathlib.py'),
1287       PosixPath('setup.py'),
1288       PosixPath('test_pathlib.py')]
1289
1290   .. seealso::
1291      :ref:`pathlib-pattern-language` documentation.
1292
1293   By default, or when the *case_sensitive* keyword-only argument is set to
1294   ``None``, this method matches paths using platform-specific casing rules:
1295   typically, case-sensitive on POSIX, and case-insensitive on Windows.
1296   Set *case_sensitive* to ``True`` or ``False`` to override this behaviour.
1297
1298   By default, or when the *recurse_symlinks* keyword-only argument is set to
1299   ``False``, this method follows symlinks except when expanding "``**``"
1300   wildcards. Set *recurse_symlinks* to ``True`` to always follow symlinks.
1301
1302   .. audit-event:: pathlib.Path.glob self,pattern pathlib.Path.glob
1303
1304   .. versionchanged:: 3.12
1305      The *case_sensitive* parameter was added.
1306
1307   .. versionchanged:: 3.13
1308      The *recurse_symlinks* parameter was added.
1309
1310   .. versionchanged:: 3.13
1311      The *pattern* parameter accepts a :term:`path-like object`.
1312
1313   .. versionchanged:: 3.13
1314      Any :exc:`OSError` exceptions raised from scanning the filesystem are
1315      suppressed. In previous versions, such exceptions are suppressed in many
1316      cases, but not all.
1317
1318
1319.. method:: Path.rglob(pattern, *, case_sensitive=None, recurse_symlinks=False)
1320
1321   Glob the given relative *pattern* recursively.  This is like calling
1322   :func:`Path.glob` with "``**/``" added in front of the *pattern*.
1323
1324   .. seealso::
1325      :ref:`pathlib-pattern-language` and :meth:`Path.glob` documentation.
1326
1327   .. audit-event:: pathlib.Path.rglob self,pattern pathlib.Path.rglob
1328
1329   .. versionchanged:: 3.12
1330      The *case_sensitive* parameter was added.
1331
1332   .. versionchanged:: 3.13
1333      The *recurse_symlinks* parameter was added.
1334
1335   .. versionchanged:: 3.13
1336      The *pattern* parameter accepts a :term:`path-like object`.
1337
1338
1339.. method:: Path.walk(top_down=True, on_error=None, follow_symlinks=False)
1340
1341   Generate the file names in a directory tree by walking the tree
1342   either top-down or bottom-up.
1343
1344   For each directory in the directory tree rooted at *self* (including
1345   *self* but excluding '.' and '..'), the method yields a 3-tuple of
1346   ``(dirpath, dirnames, filenames)``.
1347
1348   *dirpath* is a :class:`Path` to the directory currently being walked,
1349   *dirnames* is a list of strings for the names of subdirectories in *dirpath*
1350   (excluding ``'.'`` and ``'..'``), and *filenames* is a list of strings for
1351   the names of the non-directory files in *dirpath*. To get a full path
1352   (which begins with *self*) to a file or directory in *dirpath*, do
1353   ``dirpath / name``. Whether or not the lists are sorted is file
1354   system-dependent.
1355
1356   If the optional argument *top_down* is true (which is the default), the triple for a
1357   directory is generated before the triples for any of its subdirectories
1358   (directories are walked top-down).  If *top_down* is false, the triple
1359   for a directory is generated after the triples for all of its subdirectories
1360   (directories are walked bottom-up). No matter the value of *top_down*, the
1361   list of subdirectories is retrieved before the triples for the directory and
1362   its subdirectories are walked.
1363
1364   When *top_down* is true, the caller can modify the *dirnames* list in-place
1365   (for example, using :keyword:`del` or slice assignment), and :meth:`Path.walk`
1366   will only recurse into the subdirectories whose names remain in *dirnames*.
1367   This can be used to prune the search, or to impose a specific order of visiting,
1368   or even to inform :meth:`Path.walk` about directories the caller creates or
1369   renames before it resumes :meth:`Path.walk` again. Modifying *dirnames* when
1370   *top_down* is false has no effect on the behavior of :meth:`Path.walk` since the
1371   directories in *dirnames* have already been generated by the time *dirnames*
1372   is yielded to the caller.
1373
1374   By default, errors from :func:`os.scandir` are ignored.  If the optional
1375   argument *on_error* is specified, it should be a callable; it will be
1376   called with one argument, an :exc:`OSError` instance. The callable can handle the
1377   error to continue the walk or re-raise it to stop the walk. Note that the
1378   filename is available as the ``filename`` attribute of the exception object.
1379
1380   By default, :meth:`Path.walk` does not follow symbolic links, and instead adds them
1381   to the *filenames* list. Set *follow_symlinks* to true to resolve symlinks
1382   and place them in *dirnames* and *filenames* as appropriate for their targets, and
1383   consequently visit directories pointed to by symlinks (where supported).
1384
1385   .. note::
1386
1387      Be aware that setting *follow_symlinks* to true can lead to infinite
1388      recursion if a link points to a parent directory of itself. :meth:`Path.walk`
1389      does not keep track of the directories it has already visited.
1390
1391   .. note::
1392      :meth:`Path.walk` assumes the directories it walks are not modified during
1393      execution. For example, if a directory from *dirnames* has been replaced
1394      with a symlink and *follow_symlinks* is false, :meth:`Path.walk` will
1395      still try to descend into it. To prevent such behavior, remove directories
1396      from *dirnames* as appropriate.
1397
1398   .. note::
1399
1400      Unlike :func:`os.walk`, :meth:`Path.walk` lists symlinks to directories in
1401      *filenames* if *follow_symlinks* is false.
1402
1403   This example displays the number of bytes used by all files in each directory,
1404   while ignoring ``__pycache__`` directories::
1405
1406      from pathlib import Path
1407      for root, dirs, files in Path("cpython/Lib/concurrent").walk(on_error=print):
1408        print(
1409            root,
1410            "consumes",
1411            sum((root / file).stat().st_size for file in files),
1412            "bytes in",
1413            len(files),
1414            "non-directory files"
1415        )
1416        if '__pycache__' in dirs:
1417              dirs.remove('__pycache__')
1418
1419   This next example is a simple implementation of :func:`shutil.rmtree`.
1420   Walking the tree bottom-up is essential as :func:`rmdir` doesn't allow
1421   deleting a directory before it is empty::
1422
1423      # Delete everything reachable from the directory "top".
1424      # CAUTION:  This is dangerous! For example, if top == Path('/'),
1425      # it could delete all of your files.
1426      for root, dirs, files in top.walk(top_down=False):
1427          for name in files:
1428              (root / name).unlink()
1429          for name in dirs:
1430              (root / name).rmdir()
1431
1432   .. versionadded:: 3.12
1433
1434
1435Creating files and directories
1436^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1437
1438.. method:: Path.touch(mode=0o666, exist_ok=True)
1439
1440   Create a file at this given path.  If *mode* is given, it is combined
1441   with the process's ``umask`` value to determine the file mode and access
1442   flags.  If the file already exists, the function succeeds when *exist_ok*
1443   is true (and its modification time is updated to the current time),
1444   otherwise :exc:`FileExistsError` is raised.
1445
1446   .. seealso::
1447      The :meth:`~Path.open`, :meth:`~Path.write_text` and
1448      :meth:`~Path.write_bytes` methods are often used to create files.
1449
1450
1451.. method:: Path.mkdir(mode=0o777, parents=False, exist_ok=False)
1452
1453   Create a new directory at this given path.  If *mode* is given, it is
1454   combined with the process's ``umask`` value to determine the file mode
1455   and access flags.  If the path already exists, :exc:`FileExistsError`
1456   is raised.
1457
1458   If *parents* is true, any missing parents of this path are created
1459   as needed; they are created with the default permissions without taking
1460   *mode* into account (mimicking the POSIX ``mkdir -p`` command).
1461
1462   If *parents* is false (the default), a missing parent raises
1463   :exc:`FileNotFoundError`.
1464
1465   If *exist_ok* is false (the default), :exc:`FileExistsError` is
1466   raised if the target directory already exists.
1467
1468   If *exist_ok* is true, :exc:`FileExistsError` will not be raised unless the given
1469   path already exists in the file system and is not a directory (same
1470   behavior as the POSIX ``mkdir -p`` command).
1471
1472   .. versionchanged:: 3.5
1473      The *exist_ok* parameter was added.
1474
1475
1476.. method:: Path.symlink_to(target, target_is_directory=False)
1477
1478   Make this path a symbolic link pointing to *target*.
1479
1480   On Windows, a symlink represents either a file or a directory, and does not
1481   morph to the target dynamically.  If the target is present, the type of the
1482   symlink will be created to match. Otherwise, the symlink will be created
1483   as a directory if *target_is_directory* is true or a file symlink (the
1484   default) otherwise.  On non-Windows platforms, *target_is_directory* is ignored.
1485
1486   ::
1487
1488      >>> p = Path('mylink')
1489      >>> p.symlink_to('setup.py')
1490      >>> p.resolve()
1491      PosixPath('/home/antoine/pathlib/setup.py')
1492      >>> p.stat().st_size
1493      956
1494      >>> p.lstat().st_size
1495      8
1496
1497   .. note::
1498      The order of arguments (link, target) is the reverse
1499      of :func:`os.symlink`'s.
1500
1501   .. versionchanged:: 3.13
1502      Raises :exc:`UnsupportedOperation` if :func:`os.symlink` is not
1503      available. In previous versions, :exc:`NotImplementedError` was raised.
1504
1505
1506.. method:: Path.hardlink_to(target)
1507
1508   Make this path a hard link to the same file as *target*.
1509
1510   .. note::
1511      The order of arguments (link, target) is the reverse
1512      of :func:`os.link`'s.
1513
1514   .. versionadded:: 3.10
1515
1516   .. versionchanged:: 3.13
1517      Raises :exc:`UnsupportedOperation` if :func:`os.link` is not
1518      available. In previous versions, :exc:`NotImplementedError` was raised.
1519
1520
1521Renaming and deleting
1522^^^^^^^^^^^^^^^^^^^^^
1523
1524.. method:: Path.rename(target)
1525
1526   Rename this file or directory to the given *target*, and return a new
1527   :class:`!Path` instance pointing to *target*.  On Unix, if *target* exists
1528   and is a file, it will be replaced silently if the user has permission.
1529   On Windows, if *target* exists, :exc:`FileExistsError` will be raised.
1530   *target* can be either a string or another path object::
1531
1532      >>> p = Path('foo')
1533      >>> p.open('w').write('some text')
1534      9
1535      >>> target = Path('bar')
1536      >>> p.rename(target)
1537      PosixPath('bar')
1538      >>> target.open().read()
1539      'some text'
1540
1541   The target path may be absolute or relative. Relative paths are interpreted
1542   relative to the current working directory, *not* the directory of the
1543   :class:`!Path` object.
1544
1545   It is implemented in terms of :func:`os.rename` and gives the same guarantees.
1546
1547   .. versionchanged:: 3.8
1548      Added return value, return the new :class:`!Path` instance.
1549
1550
1551.. method:: Path.replace(target)
1552
1553   Rename this file or directory to the given *target*, and return a new
1554   :class:`!Path` instance pointing to *target*.  If *target* points to an
1555   existing file or empty directory, it will be unconditionally replaced.
1556
1557   The target path may be absolute or relative. Relative paths are interpreted
1558   relative to the current working directory, *not* the directory of the
1559   :class:`!Path` object.
1560
1561   .. versionchanged:: 3.8
1562      Added return value, return the new :class:`!Path` instance.
1563
1564
1565.. method:: Path.unlink(missing_ok=False)
1566
1567   Remove this file or symbolic link.  If the path points to a directory,
1568   use :func:`Path.rmdir` instead.
1569
1570   If *missing_ok* is false (the default), :exc:`FileNotFoundError` is
1571   raised if the path does not exist.
1572
1573   If *missing_ok* is true, :exc:`FileNotFoundError` exceptions will be
1574   ignored (same behavior as the POSIX ``rm -f`` command).
1575
1576   .. versionchanged:: 3.8
1577      The *missing_ok* parameter was added.
1578
1579
1580.. method:: Path.rmdir()
1581
1582   Remove this directory.  The directory must be empty.
1583
1584
1585Permissions and ownership
1586^^^^^^^^^^^^^^^^^^^^^^^^^
1587
1588.. method:: Path.owner(*, follow_symlinks=True)
1589
1590   Return the name of the user owning the file. :exc:`KeyError` is raised
1591   if the file's user identifier (UID) isn't found in the system database.
1592
1593   This method normally follows symlinks; to get the owner of the symlink, add
1594   the argument ``follow_symlinks=False``.
1595
1596   .. versionchanged:: 3.13
1597      Raises :exc:`UnsupportedOperation` if the :mod:`pwd` module is not
1598      available. In earlier versions, :exc:`NotImplementedError` was raised.
1599
1600   .. versionchanged:: 3.13
1601      The *follow_symlinks* parameter was added.
1602
1603
1604.. method:: Path.group(*, follow_symlinks=True)
1605
1606   Return the name of the group owning the file. :exc:`KeyError` is raised
1607   if the file's group identifier (GID) isn't found in the system database.
1608
1609   This method normally follows symlinks; to get the group of the symlink, add
1610   the argument ``follow_symlinks=False``.
1611
1612   .. versionchanged:: 3.13
1613      Raises :exc:`UnsupportedOperation` if the :mod:`grp` module is not
1614      available. In earlier versions, :exc:`NotImplementedError` was raised.
1615
1616   .. versionchanged:: 3.13
1617      The *follow_symlinks* parameter was added.
1618
1619
1620.. method:: Path.chmod(mode, *, follow_symlinks=True)
1621
1622   Change the file mode and permissions, like :func:`os.chmod`.
1623
1624   This method normally follows symlinks. Some Unix flavours support changing
1625   permissions on the symlink itself; on these platforms you may add the
1626   argument ``follow_symlinks=False``, or use :meth:`~Path.lchmod`.
1627
1628   ::
1629
1630      >>> p = Path('setup.py')
1631      >>> p.stat().st_mode
1632      33277
1633      >>> p.chmod(0o444)
1634      >>> p.stat().st_mode
1635      33060
1636
1637   .. versionchanged:: 3.10
1638      The *follow_symlinks* parameter was added.
1639
1640
1641.. method:: Path.lchmod(mode)
1642
1643   Like :meth:`Path.chmod` but, if the path points to a symbolic link, the
1644   symbolic link's mode is changed rather than its target's.
1645
1646
1647.. _pathlib-pattern-language:
1648
1649Pattern language
1650----------------
1651
1652The following wildcards are supported in patterns for
1653:meth:`~PurePath.full_match`, :meth:`~Path.glob` and :meth:`~Path.rglob`:
1654
1655``**`` (entire segment)
1656  Matches any number of file or directory segments, including zero.
1657``*`` (entire segment)
1658  Matches one file or directory segment.
1659``*`` (part of a segment)
1660  Matches any number of non-separator characters, including zero.
1661``?``
1662  Matches one non-separator character.
1663``[seq]``
1664  Matches one character in *seq*.
1665``[!seq]``
1666  Matches one character not in *seq*.
1667
1668For a literal match, wrap the meta-characters in brackets.
1669For example, ``"[?]"`` matches the character ``"?"``.
1670
1671The "``**``" wildcard enables recursive globbing. A few examples:
1672
1673=========================  ===========================================
1674Pattern                    Meaning
1675=========================  ===========================================
1676"``**/*``"                 Any path with at least one segment.
1677"``**/*.py``"              Any path with a final segment ending "``.py``".
1678"``assets/**``"            Any path starting with "``assets/``".
1679"``assets/**/*``"          Any path starting with "``assets/``", excluding "``assets/``" itself.
1680=========================  ===========================================
1681
1682.. note::
1683   Globbing with the "``**``" wildcard visits every directory in the tree.
1684   Large directory trees may take a long time to search.
1685
1686.. versionchanged:: 3.13
1687   Globbing with a pattern that ends with "``**``" returns both files and
1688   directories. In previous versions, only directories were returned.
1689
1690In :meth:`Path.glob` and :meth:`~Path.rglob`, a trailing slash may be added to
1691the pattern to match only directories.
1692
1693.. versionchanged:: 3.11
1694   Globbing with a pattern that ends with a pathname components separator
1695   (:data:`~os.sep` or :data:`~os.altsep`) returns only directories.
1696
1697
1698Comparison to the :mod:`glob` module
1699------------------------------------
1700
1701The patterns accepted and results generated by :meth:`Path.glob` and
1702:meth:`Path.rglob` differ slightly from those by the :mod:`glob` module:
1703
17041. Files beginning with a dot are not special in pathlib. This is
1705   like passing ``include_hidden=True`` to :func:`glob.glob`.
17062. "``**``" pattern components are always recursive in pathlib. This is like
1707   passing ``recursive=True`` to :func:`glob.glob`.
17083. "``**``" pattern components do not follow symlinks by default in pathlib.
1709   This behaviour has no equivalent in :func:`glob.glob`, but you can pass
1710   ``recurse_symlinks=True`` to :meth:`Path.glob` for compatible behaviour.
17114. Like all :class:`PurePath` and :class:`Path` objects, the values returned
1712   from :meth:`Path.glob` and :meth:`Path.rglob` don't include trailing
1713   slashes.
17145. The values returned from pathlib's ``path.glob()`` and ``path.rglob()``
1715   include the *path* as a prefix, unlike the results of
1716   ``glob.glob(root_dir=path)``.
17176. The values returned from pathlib's ``path.glob()`` and ``path.rglob()``
1718   may include *path* itself, for example when globbing "``**``", whereas the
1719   results of ``glob.glob(root_dir=path)`` never include an empty string that
1720   would correspond to *path*.
1721
1722
1723Comparison to the :mod:`os` and :mod:`os.path` modules
1724------------------------------------------------------
1725
1726pathlib implements path operations using :class:`PurePath` and :class:`Path`
1727objects, and so it's said to be *object-oriented*. On the other hand, the
1728:mod:`os` and :mod:`os.path` modules supply functions that work with low-level
1729``str`` and ``bytes`` objects, which is a more *procedural* approach. Some
1730users consider the object-oriented style to be more readable.
1731
1732Many functions in :mod:`os` and :mod:`os.path` support ``bytes`` paths and
1733:ref:`paths relative to directory descriptors <dir_fd>`. These features aren't
1734available in pathlib.
1735
1736Python's ``str`` and ``bytes`` types, and portions of the :mod:`os` and
1737:mod:`os.path` modules, are written in C and are very speedy. pathlib is
1738written in pure Python and is often slower, but rarely slow enough to matter.
1739
1740pathlib's path normalization is slightly more opinionated and consistent than
1741:mod:`os.path`. For example, whereas :func:`os.path.abspath` eliminates
1742"``..``" segments from a path, which may change its meaning if symlinks are
1743involved, :meth:`Path.absolute` preserves these segments for greater safety.
1744
1745pathlib's path normalization may render it unsuitable for some applications:
1746
17471. pathlib normalizes ``Path("my_folder/")`` to ``Path("my_folder")``, which
1748   changes a path's meaning when supplied to various operating system APIs and
1749   command-line utilities. Specifically, the absence of a trailing separator
1750   may allow the path to be resolved as either a file or directory, rather
1751   than a directory only.
17522. pathlib normalizes ``Path("./my_program")`` to ``Path("my_program")``,
1753   which changes a path's meaning when used as an executable search path, such
1754   as in a shell or when spawning a child process. Specifically, the absence
1755   of a separator in the path may force it to be looked up in :envvar:`PATH`
1756   rather than the current directory.
1757
1758As a consequence of these differences, pathlib is not a drop-in replacement
1759for :mod:`os.path`.
1760
1761
1762Corresponding tools
1763^^^^^^^^^^^^^^^^^^^
1764
1765Below is a table mapping various :mod:`os` functions to their corresponding
1766:class:`PurePath`/:class:`Path` equivalent.
1767
1768=====================================   ==============================================
1769:mod:`os` and :mod:`os.path`            :mod:`pathlib`
1770=====================================   ==============================================
1771:func:`os.path.dirname`                 :attr:`PurePath.parent`
1772:func:`os.path.basename`                :attr:`PurePath.name`
1773:func:`os.path.splitext`                :attr:`PurePath.stem`, :attr:`PurePath.suffix`
1774:func:`os.path.join`                    :meth:`PurePath.joinpath`
1775:func:`os.path.isabs`                   :meth:`PurePath.is_absolute`
1776:func:`os.path.relpath`                 :meth:`PurePath.relative_to` [1]_
1777:func:`os.path.expanduser`              :meth:`Path.expanduser` [2]_
1778:func:`os.path.realpath`                :meth:`Path.resolve`
1779:func:`os.path.abspath`                 :meth:`Path.absolute` [3]_
1780:func:`os.path.exists`                  :meth:`Path.exists`
1781:func:`os.path.isfile`                  :meth:`Path.is_file`
1782:func:`os.path.isdir`                   :meth:`Path.is_dir`
1783:func:`os.path.islink`                  :meth:`Path.is_symlink`
1784:func:`os.path.isjunction`              :meth:`Path.is_junction`
1785:func:`os.path.ismount`                 :meth:`Path.is_mount`
1786:func:`os.path.samefile`                :meth:`Path.samefile`
1787:func:`os.getcwd`                       :meth:`Path.cwd`
1788:func:`os.stat`                         :meth:`Path.stat`
1789:func:`os.lstat`                        :meth:`Path.lstat`
1790:func:`os.listdir`                      :meth:`Path.iterdir`
1791:func:`os.walk`                         :meth:`Path.walk` [4]_
1792:func:`os.mkdir`, :func:`os.makedirs`   :meth:`Path.mkdir`
1793:func:`os.link`                         :meth:`Path.hardlink_to`
1794:func:`os.symlink`                      :meth:`Path.symlink_to`
1795:func:`os.readlink`                     :meth:`Path.readlink`
1796:func:`os.rename`                       :meth:`Path.rename`
1797:func:`os.replace`                      :meth:`Path.replace`
1798:func:`os.remove`, :func:`os.unlink`    :meth:`Path.unlink`
1799:func:`os.rmdir`                        :meth:`Path.rmdir`
1800:func:`os.chmod`                        :meth:`Path.chmod`
1801:func:`os.lchmod`                       :meth:`Path.lchmod`
1802=====================================   ==============================================
1803
1804.. rubric:: Footnotes
1805
1806.. [1] :func:`os.path.relpath` calls :func:`~os.path.abspath` to make paths
1807   absolute and remove "``..``" parts, whereas :meth:`PurePath.relative_to`
1808   is a lexical operation that raises :exc:`ValueError` when its inputs'
1809   anchors differ (e.g. if one path is absolute and the other relative.)
1810.. [2] :func:`os.path.expanduser` returns the path unchanged if the home
1811   directory can't be resolved, whereas :meth:`Path.expanduser` raises
1812   :exc:`RuntimeError`.
1813.. [3] :func:`os.path.abspath` removes "``..``" components without resolving
1814   symlinks, which may change the meaning of the path, whereas
1815   :meth:`Path.absolute` leaves any "``..``" components in the path.
1816.. [4] :func:`os.walk` always follows symlinks when categorizing paths into
1817   *dirnames* and *filenames*, whereas :meth:`Path.walk` categorizes all
1818   symlinks into *filenames* when *follow_symlinks* is false (the default.)
1819