Debian Codegraph @

Doc/library/pathlib.rst

raw
1 :mod:`!pathlib` --- Object-oriented filesystem paths
2 ====================================================
3
4 .. module:: pathlib
5 :synopsis: Object-oriented filesystem paths
6
7 .. versionadded:: 3.4
8
9 **Source code:** :source:`Lib/pathlib/`
10
11 .. index:: single: path; operations
12
13 --------------
14
15 This module offers classes representing filesystem paths with semantics
16 appropriate for different operating systems. Path classes are divided
17 between :ref:`pure paths <pure-paths>`, which provide purely computational
18 operations without I/O, and :ref:`concrete paths <concrete-paths>`, which
19 inherit from pure paths but also provide I/O operations.
20
21 .. image:: pathlib-inheritance.png
22 :align: center
23 :class: invert-in-dark-mode
24 :alt: Inheritance diagram showing the classes available in pathlib. The
25 most basic class is PurePath, which has three direct subclasses:
26 PurePosixPath, PureWindowsPath, and Path. Further to these four
27 classes, there are two classes that use multiple inheritance:
28 PosixPath subclasses PurePosixPath and Path, and WindowsPath
29 subclasses PureWindowsPath and Path.
30
31 If you've never used this module before or just aren't sure which class is
32 right for your task, :class:`Path` is most likely what you need. It instantiates
33 a :ref:`concrete path <concrete-paths>` for the platform the code is running on.
34
35 Pure paths are useful in some special cases; for example:
36
37 #. If you want to manipulate Windows paths on a Unix machine (or vice versa).
38 You cannot instantiate a :class:`WindowsPath` when running on Unix, but you
39 can instantiate :class:`PureWindowsPath`.
40 #. You want to make sure that your code only manipulates paths without actually
41 accessing the OS. In this case, instantiating one of the pure classes may be
42 useful since those simply don't have any OS-accessing operations.
43
44 .. seealso::
45 :pep:`428`: The pathlib module -- object-oriented filesystem paths.
46
47 .. seealso::
48 For low-level path manipulation on strings, you can also use the
49 :mod:`os.path` module.
50
51
52 Basic use
53 ---------
54
55 Importing the main class::
56
57 >>> from pathlib import Path
58
59 Listing subdirectories::
60
61 >>> p = Path('.')
62 >>> [x for x in p.iterdir() if x.is_dir()]
63 [PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
64 PosixPath('__pycache__'), PosixPath('build')]
65
66 Listing Python source files in this directory tree::
67
68 >>> list(p.glob('**/*.py'))
69 [PosixPath('test_pathlib.py'), PosixPath('setup.py'),
70 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
71 PosixPath('build/lib/pathlib.py')]
72
73 Navigating inside a directory tree::
74
75 >>> p = Path('/etc')
76 >>> q = p / 'init.d' / 'reboot'
77 >>> q
78 PosixPath('/etc/init.d/reboot')
79 >>> q.resolve()
80 PosixPath('/etc/rc.d/init.d/halt')
81
82 Querying path properties::
83
84 >>> q.exists()
85 True
86 >>> q.is_dir()
87 False
88
89 Opening a file::
90
91 >>> with q.open() as f: f.readline()
92 ...
93 '#!/bin/bash\n'
94
95
96 Exceptions
97 ----------
98
99 .. exception:: UnsupportedOperation
100
101 An exception inheriting :exc:`NotImplementedError` that is raised when an
102 unsupported operation is called on a path object.
103
104 .. versionadded:: 3.13
105
106
107 .. _pure-paths:
108
109 Pure paths
110 ----------
111
112 Pure path objects provide path-handling operations which don't actually
113 access a filesystem. There are three ways to access these classes, which
114 we also call *flavours*:
115
116 .. class:: PurePath(*pathsegments)
117
118 A generic class that represents the system's path flavour (instantiating
119 it creates either a :class:`PurePosixPath` or a :class:`PureWindowsPath`)::
120
121 >>> PurePath('setup.py') # Running on a Unix machine
122 PurePosixPath('setup.py')
123
124 Each element of *pathsegments* can be either a string representing a
125 path segment, or an object implementing the :class:`os.PathLike` interface
126 where the :meth:`~os.PathLike.__fspath__` method returns a string,
127 such as another path object::
128
129 >>> PurePath('foo', 'some/path', 'bar')
130 PurePosixPath('foo/some/path/bar')
131 >>> PurePath(Path('foo'), Path('bar'))
132 PurePosixPath('foo/bar')
133
134 When *pathsegments* is empty, the current directory is assumed::
135
136 >>> PurePath()
137 PurePosixPath('.')
138
139 If a segment is an absolute path, all previous segments are ignored
140 (like :func:`os.path.join`)::
141
142 >>> PurePath('/etc', '/usr', 'lib64')
143 PurePosixPath('/usr/lib64')
144 >>> PureWindowsPath('c:/Windows', 'd:bar')
145 PureWindowsPath('d:bar')
146
147 On Windows, the drive is not reset when a rooted relative path
148 segment (e.g., ``r'\foo'``) is encountered::
149
150 >>> PureWindowsPath('c:/Windows', '/Program Files')
151 PureWindowsPath('c:/Program Files')
152
153 Spurious slashes and single dots are collapsed, but double dots (``'..'``)
154 and leading double slashes (``'//'``) are not, since this would change the
155 meaning of a path for various reasons (e.g. symbolic links, UNC paths)::
156
157 >>> PurePath('foo//bar')
158 PurePosixPath('foo/bar')
159 >>> PurePath('//foo/bar')
160 PurePosixPath('//foo/bar')
161 >>> PurePath('foo/./bar')
162 PurePosixPath('foo/bar')
163 >>> PurePath('foo/../bar')
164 PurePosixPath('foo/../bar')
165
166 (a naïve approach would make ``PurePosixPath('foo/../bar')`` equivalent
167 to ``PurePosixPath('bar')``, which is wrong if ``foo`` is a symbolic link
168 to another directory)
169
170 Pure path objects implement the :class:`os.PathLike` interface, allowing them
171 to be used anywhere the interface is accepted.
172
173 .. versionchanged:: 3.6
174 Added support for the :class:`os.PathLike` interface.
175
176 .. class:: PurePosixPath(*pathsegments)
177
178 A subclass of :class:`PurePath`, this path flavour represents non-Windows
179 filesystem paths::
180
181 >>> PurePosixPath('/etc/hosts')
182 PurePosixPath('/etc/hosts')
183
184 *pathsegments* is specified similarly to :class:`PurePath`.
185
186 .. class:: PureWindowsPath(*pathsegments)
187
188 A subclass of :class:`PurePath`, this path flavour represents Windows
189 filesystem paths, including `UNC paths`_::
190
191 >>> PureWindowsPath('c:/', 'Users', 'Ximénez')
192 PureWindowsPath('c:/Users/Ximénez')
193 >>> PureWindowsPath('//server/share/file')
194 PureWindowsPath('//server/share/file')
195
196 *pathsegments* is specified similarly to :class:`PurePath`.
197
198 .. _unc paths: https://en.wikipedia.org/wiki/Path_(computing)#UNC
199
200 Regardless of the system you're running on, you can instantiate all of
201 these classes, since they don't provide any operation that does system calls.
202
203
204 General properties
205 ^^^^^^^^^^^^^^^^^^
206
207 Paths are immutable and :term:`hashable`. Paths of a same flavour are comparable
208 and orderable. These properties respect the flavour's case-folding
209 semantics::
210
211 >>> PurePosixPath('foo') == PurePosixPath('FOO')
212 False
213 >>> PureWindowsPath('foo') == PureWindowsPath('FOO')
214 True
215 >>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
216 True
217 >>> PureWindowsPath('C:') < PureWindowsPath('d:')
218 True
219
220 Paths of a different flavour compare unequal and cannot be ordered::
221
222 >>> PureWindowsPath('foo') == PurePosixPath('foo')
223 False
224 >>> PureWindowsPath('foo') < PurePosixPath('foo')
225 Traceback (most recent call last):
226 File "<stdin>", line 1, in <module>
227 TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'
228
229
230 Operators
231 ^^^^^^^^^
232
233 The slash operator helps create child paths, like :func:`os.path.join`.
234 If the argument is an absolute path, the previous path is ignored.
235 On Windows, the drive is not reset when the argument is a rooted
236 relative path (e.g., ``r'\foo'``)::
237
238 >>> p = PurePath('/etc')
239 >>> p
240 PurePosixPath('/etc')
241 >>> p / 'init.d' / 'apache2'
242 PurePosixPath('/etc/init.d/apache2')
243 >>> q = PurePath('bin')
244 >>> '/usr' / q
245 PurePosixPath('/usr/bin')
246 >>> p / '/an_absolute_path'
247 PurePosixPath('/an_absolute_path')
248 >>> PureWindowsPath('c:/Windows', '/Program Files')
249 PureWindowsPath('c:/Program Files')
250
251 A path object can be used anywhere an object implementing :class:`os.PathLike`
252 is accepted::
253
254 >>> import os
255 >>> p = PurePath('/etc')
256 >>> os.fspath(p)
257 '/etc'
258
259 The string representation of a path is the raw filesystem path itself
260 (in native form, e.g. with backslashes under Windows), which you can
261 pass to any function taking a file path as a string::
262
263 >>> p = PurePath('/etc')
264 >>> str(p)
265 '/etc'
266 >>> p = PureWindowsPath('c:/Program Files')
267 >>> str(p)
268 'c:\\Program Files'
269
270 Similarly, calling :class:`bytes` on a path gives the raw filesystem path as a
271 bytes object, as encoded by :func:`os.fsencode`::
272
273 >>> bytes(p)
274 b'/etc'
275
276 .. note::
277 Calling :class:`bytes` is only recommended under Unix. Under Windows,
278 the unicode form is the canonical representation of filesystem paths.
279
280
281 Accessing individual parts
282 ^^^^^^^^^^^^^^^^^^^^^^^^^^
283
284 To access the individual "parts" (components) of a path, use the following
285 property:
286
287 .. attribute:: PurePath.parts
288
289 A tuple giving access to the path's various components::
290
291 >>> p = PurePath('/usr/bin/python3')
292 >>> p.parts
293 ('/', 'usr', 'bin', 'python3')
294
295 >>> p = PureWindowsPath('c:/Program Files/PSF')
296 >>> p.parts
297 ('c:\\', 'Program Files', 'PSF')
298
299 (note how the drive and local root are regrouped in a single part)
300
301
302 Methods and properties
303 ^^^^^^^^^^^^^^^^^^^^^^
304
305 .. testsetup::
306
307 from pathlib import PurePath, PurePosixPath, PureWindowsPath
308
309 Pure paths provide the following methods and properties:
310
311 .. attribute:: PurePath.parser
312
313 The implementation of the :mod:`os.path` module used for low-level path
314 parsing and joining: either :mod:`!posixpath` or :mod:`!ntpath`.
315
316 .. versionadded:: 3.13
317
318 .. attribute:: PurePath.drive
319
320 A string representing the drive letter or name, if any::
321
322 >>> PureWindowsPath('c:/Program Files/').drive
323 'c:'
324 >>> PureWindowsPath('/Program Files/').drive
325 ''
326 >>> PurePosixPath('/etc').drive
327 ''
328
329 UNC shares are also considered drives::
330
331 >>> PureWindowsPath('//host/share/foo.txt').drive
332 '\\\\host\\share'
333
334 .. attribute:: PurePath.root
335
336 A string representing the (local or global) root, if any::
337
338 >>> PureWindowsPath('c:/Program Files/').root
339 '\\'
340 >>> PureWindowsPath('c:Program Files/').root
341 ''
342 >>> PurePosixPath('/etc').root
343 '/'
344
345 UNC shares always have a root::
346
347 >>> PureWindowsPath('//host/share').root
348 '\\'
349
350 If the path starts with more than two successive slashes,
351 :class:`~pathlib.PurePosixPath` collapses them::
352
353 >>> PurePosixPath('//etc').root
354 '//'
355 >>> PurePosixPath('///etc').root
356 '/'
357 >>> PurePosixPath('////etc').root
358 '/'
359
360 .. note::
361
362 This behavior conforms to *The Open Group Base Specifications Issue 6*,
363 paragraph `4.11 Pathname Resolution
364 <https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11>`_:
365
366 *"A pathname that begins with two successive slashes may be interpreted in
367 an implementation-defined manner, although more than two leading slashes
368 shall be treated as a single slash."*
369
370 .. attribute:: PurePath.anchor
371
372 The concatenation of the drive and root::
373
374 >>> PureWindowsPath('c:/Program Files/').anchor
375 'c:\\'
376 >>> PureWindowsPath('c:Program Files/').anchor
377 'c:'
378 >>> PurePosixPath('/etc').anchor
379 '/'
380 >>> PureWindowsPath('//host/share').anchor
381 '\\\\host\\share\\'
382
383
384 .. attribute:: PurePath.parents
385
386 An immutable sequence providing access to the logical ancestors of
387 the path::
388
389 >>> p = PureWindowsPath('c:/foo/bar/setup.py')
390 >>> p.parents[0]
391 PureWindowsPath('c:/foo/bar')
392 >>> p.parents[1]
393 PureWindowsPath('c:/foo')
394 >>> p.parents[2]
395 PureWindowsPath('c:/')
396
397 .. versionchanged:: 3.10
398 The parents sequence now supports :term:`slices <slice>` and negative index values.
399
400 .. attribute:: PurePath.parent
401
402 The logical parent of the path::
403
404 >>> p = PurePosixPath('/a/b/c/d')
405 >>> p.parent
406 PurePosixPath('/a/b/c')
407
408 You cannot go past an anchor, or empty path::
409
410 >>> p = PurePosixPath('/')
411 >>> p.parent
412 PurePosixPath('/')
413 >>> p = PurePosixPath('.')
414 >>> p.parent
415 PurePosixPath('.')
416
417 .. note::
418 This is a purely lexical operation, hence the following behaviour::
419
420 >>> p = PurePosixPath('foo/..')
421 >>> p.parent
422 PurePosixPath('foo')
423
424 If you want to walk an arbitrary filesystem path upwards, it is
425 recommended to first call :meth:`Path.resolve` so as to resolve
426 symlinks and eliminate ``".."`` components.
427
428
429 .. attribute:: PurePath.name
430
431 A string representing the final path component, excluding the drive and
432 root, if any::
433
434 >>> PurePosixPath('my/library/setup.py').name
435 'setup.py'
436
437 UNC drive names are not considered::
438
439 >>> PureWindowsPath('//some/share/setup.py').name
440 'setup.py'
441 >>> PureWindowsPath('//some/share').name
442 ''
443
444
445 .. attribute:: PurePath.suffix
446
447 The last dot-separated portion of the final component, if any::
448
449 >>> PurePosixPath('my/library/setup.py').suffix
450 '.py'
451 >>> PurePosixPath('my/library.tar.gz').suffix
452 '.gz'
453 >>> PurePosixPath('my/library').suffix
454 ''
455
456 This is commonly called the file extension.
457
458 .. 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
750 Concrete paths
751 --------------
752
753 Concrete paths are subclasses of the pure path classes. In addition to
754 operations provided by the latter, they also provide methods to do system
755 calls 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
798 You can only instantiate the class flavour that corresponds to your system
799 (allowing system calls on non-compatible path flavours could lead to
800 bugs 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
816 Some concrete path methods can raise an :exc:`OSError` if a system call fails
817 (for example because the path doesn't exist).
818
819
820 Parsing and generating URIs
821 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
822
823 Concrete path objects can be created from, and represented as, 'file' URIs
824 conforming 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
881 Expanding 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
982 Querying 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
1163 Reading 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
1247 Reading 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 .. note::
1291 The paths are returned in no particular order.
1292 If you need a specific order, sort the results.
1293
1294 .. seealso::
1295 :ref:`pathlib-pattern-language` documentation.
1296
1297 By default, or when the *case_sensitive* keyword-only argument is set to
1298 ``None``, this method matches paths using platform-specific casing rules:
1299 typically, case-sensitive on POSIX, and case-insensitive on Windows.
1300 Set *case_sensitive* to ``True`` or ``False`` to override this behaviour.
1301
1302 By default, or when the *recurse_symlinks* keyword-only argument is set to
1303 ``False``, this method follows symlinks except when expanding "``**``"
1304 wildcards. Set *recurse_symlinks* to ``True`` to always follow symlinks.
1305
1306 .. note::
1307 Any :exc:`OSError` exceptions raised from scanning the filesystem are
1308 suppressed. This includes :exc:`PermissionError` when accessing
1309 directories without read permission.
1310
1311 .. audit-event:: pathlib.Path.glob self,pattern pathlib.Path.glob
1312
1313 .. versionchanged:: 3.12
1314 The *case_sensitive* parameter was added.
1315
1316 .. versionchanged:: 3.13
1317 The *recurse_symlinks* parameter was added.
1318
1319 .. versionchanged:: 3.13
1320 The *pattern* parameter accepts a :term:`path-like object`.
1321
1322 .. versionchanged:: 3.13
1323 Any :exc:`OSError` exceptions raised from scanning the filesystem are
1324 suppressed. In previous versions, such exceptions are suppressed in many
1325 cases, but not all.
1326
1327
1328 .. method:: Path.rglob(pattern, *, case_sensitive=None, recurse_symlinks=False)
1329
1330 Glob the given relative *pattern* recursively. This is like calling
1331 :func:`Path.glob` with "``**/``" added in front of the *pattern*.
1332
1333 .. note::
1334 The paths are returned in no particular order.
1335 If you need a specific order, sort the results.
1336
1337 .. note::
1338 Any :exc:`OSError` exceptions raised from scanning the filesystem are
1339 suppressed. This includes :exc:`PermissionError` when accessing
1340 directories without read permission.
1341
1342 .. seealso::
1343 :ref:`pathlib-pattern-language` and :meth:`Path.glob` documentation.
1344
1345 .. audit-event:: pathlib.Path.rglob self,pattern pathlib.Path.rglob
1346
1347 .. versionchanged:: 3.12
1348 The *case_sensitive* parameter was added.
1349
1350 .. versionchanged:: 3.13
1351 The *recurse_symlinks* parameter was added.
1352
1353 .. versionchanged:: 3.13
1354 The *pattern* parameter accepts a :term:`path-like object`.
1355
1356
1357 .. method:: Path.walk(top_down=True, on_error=None, follow_symlinks=False)
1358
1359 Generate the file names in a directory tree by walking the tree
1360 either top-down or bottom-up.
1361
1362 For each directory in the directory tree rooted at *self* (including
1363 *self* but excluding '.' and '..'), the method yields a 3-tuple of
1364 ``(dirpath, dirnames, filenames)``.
1365
1366 *dirpath* is a :class:`Path` to the directory currently being walked,
1367 *dirnames* is a list of strings for the names of subdirectories in *dirpath*
1368 (excluding ``'.'`` and ``'..'``), and *filenames* is a list of strings for
1369 the names of the non-directory files in *dirpath*. To get a full path
1370 (which begins with *self*) to a file or directory in *dirpath*, do
1371 ``dirpath / name``. Whether or not the lists are sorted is file
1372 system-dependent.
1373
1374 If the optional argument *top_down* is true (which is the default), the triple for a
1375 directory is generated before the triples for any of its subdirectories
1376 (directories are walked top-down). If *top_down* is false, the triple
1377 for a directory is generated after the triples for all of its subdirectories
1378 (directories are walked bottom-up). No matter the value of *top_down*, the
1379 list of subdirectories is retrieved before the triples for the directory and
1380 its subdirectories are walked.
1381
1382 When *top_down* is true, the caller can modify the *dirnames* list in-place
1383 (for example, using :keyword:`del` or slice assignment), and :meth:`Path.walk`
1384 will only recurse into the subdirectories whose names remain in *dirnames*.
1385 This can be used to prune the search, or to impose a specific order of visiting,
1386 or even to inform :meth:`Path.walk` about directories the caller creates or
1387 renames before it resumes :meth:`Path.walk` again. Modifying *dirnames* when
1388 *top_down* is false has no effect on the behavior of :meth:`Path.walk` since the
1389 directories in *dirnames* have already been generated by the time *dirnames*
1390 is yielded to the caller.
1391
1392 By default, errors from :func:`os.scandir` are ignored. If the optional
1393 argument *on_error* is specified, it should be a callable; it will be
1394 called with one argument, an :exc:`OSError` instance. The callable can handle the
1395 error to continue the walk or re-raise it to stop the walk. Note that the
1396 filename is available as the ``filename`` attribute of the exception object.
1397
1398 By default, :meth:`Path.walk` does not follow symbolic links, and instead adds them
1399 to the *filenames* list. Set *follow_symlinks* to true to resolve symlinks
1400 and place them in *dirnames* and *filenames* as appropriate for their targets, and
1401 consequently visit directories pointed to by symlinks (where supported).
1402
1403 .. note::
1404
1405 Be aware that setting *follow_symlinks* to true can lead to infinite
1406 recursion if a link points to a parent directory of itself. :meth:`Path.walk`
1407 does not keep track of the directories it has already visited.
1408
1409 .. note::
1410 :meth:`Path.walk` assumes the directories it walks are not modified during
1411 execution. For example, if a directory from *dirnames* has been replaced
1412 with a symlink and *follow_symlinks* is false, :meth:`Path.walk` will
1413 still try to descend into it. To prevent such behavior, remove directories
1414 from *dirnames* as appropriate.
1415
1416 .. note::
1417
1418 Unlike :func:`os.walk`, :meth:`Path.walk` lists symlinks to directories in
1419 *filenames* if *follow_symlinks* is false.
1420
1421 This example displays the number of bytes used by all files in each directory,
1422 while ignoring ``__pycache__`` directories::
1423
1424 from pathlib import Path
1425 for root, dirs, files in Path("cpython/Lib/concurrent").walk(on_error=print):
1426 print(
1427 root,
1428 "consumes",
1429 sum((root / file).stat().st_size for file in files),
1430 "bytes in",
1431 len(files),
1432 "non-directory files"
1433 )
1434 if '__pycache__' in dirs:
1435 dirs.remove('__pycache__')
1436
1437 This next example is a simple implementation of :func:`shutil.rmtree`.
1438 Walking the tree bottom-up is essential as :func:`rmdir` doesn't allow
1439 deleting a directory before it is empty::
1440
1441 # Delete everything reachable from the directory "top".
1442 # CAUTION: This is dangerous! For example, if top == Path('/'),
1443 # it could delete all of your files.
1444 for root, dirs, files in top.walk(top_down=False):
1445 for name in files:
1446 (root / name).unlink()
1447 for name in dirs:
1448 (root / name).rmdir()
1449
1450 .. versionadded:: 3.12
1451
1452
1453 Creating files and directories
1454 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1455
1456 .. method:: Path.touch(mode=0o666, exist_ok=True)
1457
1458 Create a file at this given path. If *mode* is given, it is combined
1459 with the process's ``umask`` value to determine the file mode and access
1460 flags. If the file already exists, the function succeeds when *exist_ok*
1461 is true (and its modification time is updated to the current time),
1462 otherwise :exc:`FileExistsError` is raised.
1463
1464 .. seealso::
1465 The :meth:`~Path.open`, :meth:`~Path.write_text` and
1466 :meth:`~Path.write_bytes` methods are often used to create files.
1467
1468
1469 .. method:: Path.mkdir(mode=0o777, parents=False, exist_ok=False)
1470
1471 Create a new directory at this given path. If *mode* is given, it is
1472 combined with the process's ``umask`` value to determine the file mode
1473 and access flags. If the path already exists, :exc:`FileExistsError`
1474 is raised.
1475
1476 If *parents* is true, any missing parents of this path are created
1477 as needed; they are created with the default permissions without taking
1478 *mode* into account (mimicking the POSIX ``mkdir -p`` command).
1479
1480 If *parents* is false (the default), a missing parent raises
1481 :exc:`FileNotFoundError`.
1482
1483 If *exist_ok* is false (the default), :exc:`FileExistsError` is
1484 raised if the target directory already exists.
1485
1486 If *exist_ok* is true, :exc:`FileExistsError` will not be raised unless the given
1487 path already exists in the file system and is not a directory (same
1488 behavior as the POSIX ``mkdir -p`` command).
1489
1490 .. versionchanged:: 3.5
1491 The *exist_ok* parameter was added.
1492
1493
1494 .. method:: Path.symlink_to(target, target_is_directory=False)
1495
1496 Make this path a symbolic link pointing to *target*.
1497
1498 On Windows, a symlink represents either a file or a directory, and does not
1499 morph to the target dynamically. If the target is present, the type of the
1500 symlink will be created to match. Otherwise, the symlink will be created
1501 as a directory if *target_is_directory* is true or a file symlink (the
1502 default) otherwise. On non-Windows platforms, *target_is_directory* is ignored.
1503
1504 ::
1505
1506 >>> p = Path('mylink')
1507 >>> p.symlink_to('setup.py')
1508 >>> p.resolve()
1509 PosixPath('/home/antoine/pathlib/setup.py')
1510 >>> p.stat().st_size
1511 956
1512 >>> p.lstat().st_size
1513 8
1514
1515 .. note::
1516 The order of arguments (link, target) is the reverse
1517 of :func:`os.symlink`'s.
1518
1519 .. versionchanged:: 3.13
1520 Raises :exc:`UnsupportedOperation` if :func:`os.symlink` is not
1521 available. In previous versions, :exc:`NotImplementedError` was raised.
1522
1523
1524 .. method:: Path.hardlink_to(target)
1525
1526 Make this path a hard link to the same file as *target*.
1527
1528 .. note::
1529 The order of arguments (link, target) is the reverse
1530 of :func:`os.link`'s.
1531
1532 .. versionadded:: 3.10
1533
1534 .. versionchanged:: 3.13
1535 Raises :exc:`UnsupportedOperation` if :func:`os.link` is not
1536 available. In previous versions, :exc:`NotImplementedError` was raised.
1537
1538
1539 Renaming and deleting
1540 ^^^^^^^^^^^^^^^^^^^^^
1541
1542 .. method:: Path.rename(target)
1543
1544 Rename this file or directory to the given *target*, and return a new
1545 :class:`!Path` instance pointing to *target*. On Unix, if *target* exists
1546 and is a file, it will be replaced silently if the user has permission.
1547 On Windows, if *target* exists, :exc:`FileExistsError` will be raised.
1548 *target* can be either a string or another path object::
1549
1550 >>> p = Path('foo')
1551 >>> p.open('w').write('some text')
1552 9
1553 >>> target = Path('bar')
1554 >>> p.rename(target)
1555 PosixPath('bar')
1556 >>> target.open().read()
1557 'some text'
1558
1559 The target path may be absolute or relative. Relative paths are interpreted
1560 relative to the current working directory, *not* the directory of the
1561 :class:`!Path` object.
1562
1563 It is implemented in terms of :func:`os.rename` and gives the same guarantees.
1564
1565 .. versionchanged:: 3.8
1566 Added return value, return the new :class:`!Path` instance.
1567
1568
1569 .. method:: Path.replace(target)
1570
1571 Rename this file or directory to the given *target*, and return a new
1572 :class:`!Path` instance pointing to *target*. If *target* points to an
1573 existing file or empty directory, it will be unconditionally replaced.
1574
1575 The target path may be absolute or relative. Relative paths are interpreted
1576 relative to the current working directory, *not* the directory of the
1577 :class:`!Path` object.
1578
1579 .. versionchanged:: 3.8
1580 Added return value, return the new :class:`!Path` instance.
1581
1582
1583 .. method:: Path.unlink(missing_ok=False)
1584
1585 Remove this file or symbolic link. If the path points to a directory,
1586 use :func:`Path.rmdir` instead.
1587
1588 If *missing_ok* is false (the default), :exc:`FileNotFoundError` is
1589 raised if the path does not exist.
1590
1591 If *missing_ok* is true, :exc:`FileNotFoundError` exceptions will be
1592 ignored (same behavior as the POSIX ``rm -f`` command).
1593
1594 .. versionchanged:: 3.8
1595 The *missing_ok* parameter was added.
1596
1597
1598 .. method:: Path.rmdir()
1599
1600 Remove this directory. The directory must be empty.
1601
1602
1603 Permissions and ownership
1604 ^^^^^^^^^^^^^^^^^^^^^^^^^
1605
1606 .. method:: Path.owner(*, follow_symlinks=True)
1607
1608 Return the name of the user owning the file. :exc:`KeyError` is raised
1609 if the file's user identifier (UID) isn't found in the system database.
1610
1611 This method normally follows symlinks; to get the owner of the symlink, add
1612 the argument ``follow_symlinks=False``.
1613
1614 .. versionchanged:: 3.13
1615 Raises :exc:`UnsupportedOperation` if the :mod:`pwd` module is not
1616 available. In earlier versions, :exc:`NotImplementedError` was raised.
1617
1618 .. versionchanged:: 3.13
1619 The *follow_symlinks* parameter was added.
1620
1621
1622 .. method:: Path.group(*, follow_symlinks=True)
1623
1624 Return the name of the group owning the file. :exc:`KeyError` is raised
1625 if the file's group identifier (GID) isn't found in the system database.
1626
1627 This method normally follows symlinks; to get the group of the symlink, add
1628 the argument ``follow_symlinks=False``.
1629
1630 .. versionchanged:: 3.13
1631 Raises :exc:`UnsupportedOperation` if the :mod:`grp` module is not
1632 available. In earlier versions, :exc:`NotImplementedError` was raised.
1633
1634 .. versionchanged:: 3.13
1635 The *follow_symlinks* parameter was added.
1636
1637
1638 .. method:: Path.chmod(mode, *, follow_symlinks=True)
1639
1640 Change the file mode and permissions, like :func:`os.chmod`.
1641
1642 This method normally follows symlinks. Some Unix flavours support changing
1643 permissions on the symlink itself; on these platforms you may add the
1644 argument ``follow_symlinks=False``, or use :meth:`~Path.lchmod`.
1645
1646 ::
1647
1648 >>> p = Path('setup.py')
1649 >>> p.stat().st_mode
1650 33277
1651 >>> p.chmod(0o444)
1652 >>> p.stat().st_mode
1653 33060
1654
1655 .. versionchanged:: 3.10
1656 The *follow_symlinks* parameter was added.
1657
1658
1659 .. method:: Path.lchmod(mode)
1660
1661 Like :meth:`Path.chmod` but, if the path points to a symbolic link, the
1662 symbolic link's mode is changed rather than its target's.
1663
1664
1665 .. _pathlib-pattern-language:
1666
1667 Pattern language
1668 ----------------
1669
1670 The following wildcards are supported in patterns for
1671 :meth:`~PurePath.full_match`, :meth:`~Path.glob` and :meth:`~Path.rglob`:
1672
1673 ``**`` (entire segment)
1674 Matches any number of file or directory segments, including zero.
1675 ``*`` (entire segment)
1676 Matches one file or directory segment.
1677 ``*`` (part of a segment)
1678 Matches any number of non-separator characters, including zero.
1679 ``?``
1680 Matches one non-separator character.
1681 ``[seq]``
1682 Matches one character in *seq*, where *seq* is a sequence of characters.
1683 Range expressions are supported; for example, ``[a-z]`` matches any lowercase ASCII letter.
1684 Multiple ranges can be combined: ``[a-zA-Z0-9_]`` matches any ASCII letter, digit, or underscore.
1685
1686 ``[!seq]``
1687 Matches one character not in *seq*, where *seq* follows the same rules as above.
1688
1689 For a literal match, wrap the meta-characters in brackets.
1690 For example, ``"[?]"`` matches the character ``"?"``.
1691
1692 The "``**``" wildcard enables recursive globbing. A few examples:
1693
1694 ========================= ===========================================
1695 Pattern Meaning
1696 ========================= ===========================================
1697 "``**/*``" Any path with at least one segment.
1698 "``**/*.py``" Any path with a final segment ending "``.py``".
1699 "``assets/**``" Any path starting with "``assets/``".
1700 "``assets/**/*``" Any path starting with "``assets/``", excluding "``assets/``" itself.
1701 ========================= ===========================================
1702
1703 .. note::
1704 Globbing with the "``**``" wildcard visits every directory in the tree.
1705 Large directory trees may take a long time to search.
1706
1707 .. versionchanged:: 3.13
1708 Globbing with a pattern that ends with "``**``" returns both files and
1709 directories. In previous versions, only directories were returned.
1710
1711 In :meth:`Path.glob` and :meth:`~Path.rglob`, a trailing slash may be added to
1712 the pattern to match only directories.
1713
1714 .. versionchanged:: 3.11
1715 Globbing with a pattern that ends with a pathname components separator
1716 (:data:`~os.sep` or :data:`~os.altsep`) returns only directories.
1717
1718
1719 Comparison to the :mod:`glob` module
1720 ------------------------------------
1721
1722 The patterns accepted and results generated by :meth:`Path.glob` and
1723 :meth:`Path.rglob` differ slightly from those by the :mod:`glob` module:
1724
1725 1. Files beginning with a dot are not special in pathlib. This is
1726 like passing ``include_hidden=True`` to :func:`glob.glob`.
1727 2. "``**``" pattern components are always recursive in pathlib. This is like
1728 passing ``recursive=True`` to :func:`glob.glob`.
1729 3. "``**``" pattern components do not follow symlinks by default in pathlib.
1730 This behaviour has no equivalent in :func:`glob.glob`, but you can pass
1731 ``recurse_symlinks=True`` to :meth:`Path.glob` for compatible behaviour.
1732 4. Like all :class:`PurePath` and :class:`Path` objects, the values returned
1733 from :meth:`Path.glob` and :meth:`Path.rglob` don't include trailing
1734 slashes.
1735 5. The values returned from pathlib's ``path.glob()`` and ``path.rglob()``
1736 include the *path* as a prefix, unlike the results of
1737 ``glob.glob(root_dir=path)``.
1738 6. The values returned from pathlib's ``path.glob()`` and ``path.rglob()``
1739 may include *path* itself, for example when globbing "``**``", whereas the
1740 results of ``glob.glob(root_dir=path)`` never include an empty string that
1741 would correspond to *path*.
1742
1743
1744 Comparison to the :mod:`os` and :mod:`os.path` modules
1745 ------------------------------------------------------
1746
1747 pathlib implements path operations using :class:`PurePath` and :class:`Path`
1748 objects, and so it's said to be *object-oriented*. On the other hand, the
1749 :mod:`os` and :mod:`os.path` modules supply functions that work with low-level
1750 ``str`` and ``bytes`` objects, which is a more *procedural* approach. Some
1751 users consider the object-oriented style to be more readable.
1752
1753 Many functions in :mod:`os` and :mod:`os.path` support ``bytes`` paths and
1754 :ref:`paths relative to directory descriptors <dir_fd>`. These features aren't
1755 available in pathlib.
1756
1757 Python's ``str`` and ``bytes`` types, and portions of the :mod:`os` and
1758 :mod:`os.path` modules, are written in C and are very speedy. pathlib is
1759 written in pure Python and is often slower, but rarely slow enough to matter.
1760
1761 pathlib's path normalization is slightly more opinionated and consistent than
1762 :mod:`os.path`. For example, whereas :func:`os.path.abspath` eliminates
1763 "``..``" segments from a path, which may change its meaning if symlinks are
1764 involved, :meth:`Path.absolute` preserves these segments for greater safety.
1765
1766 pathlib's path normalization may render it unsuitable for some applications:
1767
1768 1. pathlib normalizes ``Path("my_folder/")`` to ``Path("my_folder")``, which
1769 changes a path's meaning when supplied to various operating system APIs and
1770 command-line utilities. Specifically, the absence of a trailing separator
1771 may allow the path to be resolved as either a file or directory, rather
1772 than a directory only.
1773 2. pathlib normalizes ``Path("./my_program")`` to ``Path("my_program")``,
1774 which changes a path's meaning when used as an executable search path, such
1775 as in a shell or when spawning a child process. Specifically, the absence
1776 of a separator in the path may force it to be looked up in :envvar:`PATH`
1777 rather than the current directory.
1778
1779 As a consequence of these differences, pathlib is not a drop-in replacement
1780 for :mod:`os.path`.
1781
1782
1783 Corresponding tools
1784 ^^^^^^^^^^^^^^^^^^^
1785
1786 Below is a table mapping various :mod:`os` functions to their corresponding
1787 :class:`PurePath`/:class:`Path` equivalent.
1788
1789 ===================================== ==============================================
1790 :mod:`os` and :mod:`os.path` :mod:`pathlib`
1791 ===================================== ==============================================
1792 :func:`os.path.dirname` :attr:`PurePath.parent`
1793 :func:`os.path.basename` :attr:`PurePath.name`
1794 :func:`os.path.splitext` :attr:`PurePath.stem`, :attr:`PurePath.suffix`
1795 :func:`os.path.join` :meth:`PurePath.joinpath`
1796 :func:`os.path.isabs` :meth:`PurePath.is_absolute`
1797 :func:`os.path.relpath` :meth:`PurePath.relative_to` [1]_
1798 :func:`os.path.expanduser` :meth:`Path.expanduser` [2]_
1799 :func:`os.path.realpath` :meth:`Path.resolve`
1800 :func:`os.path.abspath` :meth:`Path.absolute` [3]_
1801 :func:`os.path.exists` :meth:`Path.exists`
1802 :func:`os.path.isfile` :meth:`Path.is_file`
1803 :func:`os.path.isdir` :meth:`Path.is_dir`
1804 :func:`os.path.islink` :meth:`Path.is_symlink`
1805 :func:`os.path.isjunction` :meth:`Path.is_junction`
1806 :func:`os.path.ismount` :meth:`Path.is_mount`
1807 :func:`os.path.samefile` :meth:`Path.samefile`
1808 :func:`os.getcwd` :meth:`Path.cwd`
1809 :func:`os.stat` :meth:`Path.stat`
1810 :func:`os.lstat` :meth:`Path.lstat`
1811 :func:`os.listdir` :meth:`Path.iterdir`
1812 :func:`os.walk` :meth:`Path.walk` [4]_
1813 :func:`os.mkdir`, :func:`os.makedirs` :meth:`Path.mkdir`
1814 :func:`os.link` :meth:`Path.hardlink_to`
1815 :func:`os.symlink` :meth:`Path.symlink_to`
1816 :func:`os.readlink` :meth:`Path.readlink`
1817 :func:`os.rename` :meth:`Path.rename`
1818 :func:`os.replace` :meth:`Path.replace`
1819 :func:`os.remove`, :func:`os.unlink` :meth:`Path.unlink`
1820 :func:`os.rmdir` :meth:`Path.rmdir`
1821 :func:`os.chmod` :meth:`Path.chmod`
1822 :func:`os.lchmod` :meth:`Path.lchmod`
1823 ===================================== ==============================================
1824
1825 .. rubric:: Footnotes
1826
1827 .. [1] :func:`os.path.relpath` calls :func:`~os.path.abspath` to make paths
1828 absolute and remove "``..``" parts, whereas :meth:`PurePath.relative_to`
1829 is a lexical operation that raises :exc:`ValueError` when its inputs'
1830 anchors differ (e.g. if one path is absolute and the other relative.)
1831 .. [2] :func:`os.path.expanduser` returns the path unchanged if the home
1832 directory can't be resolved, whereas :meth:`Path.expanduser` raises
1833 :exc:`RuntimeError`.
1834 .. [3] :func:`os.path.abspath` removes "``..``" components without resolving
1835 symlinks, which may change the meaning of the path, whereas
1836 :meth:`Path.absolute` leaves any "``..``" components in the path.
1837 .. [4] :func:`os.walk` always follows symlinks when categorizing paths into
1838 *dirnames* and *filenames*, whereas :meth:`Path.walk` categorizes all
1839 symlinks into *filenames* when *follow_symlinks* is false (the default.)