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