blob: 0c9bd0d940ae50e705be2cbd052da2f6ef560c31 [file] [log] [blame]
Antoine Pitrou31119e42013-11-22 17:38:12 +01001
2:mod:`pathlib` --- Object-oriented filesystem paths
3===================================================
4
5.. module:: pathlib
6 :synopsis: Object-oriented filesystem paths
7
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04008.. versionadded:: 3.4
9
10**Source code:** :source:`Lib/pathlib.py`
11
Antoine Pitrou31119e42013-11-22 17:38:12 +010012.. index:: single: path; operations
13
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040014--------------
Antoine Pitrou31119e42013-11-22 17:38:12 +010015
Antoine Pitrou31119e42013-11-22 17:38:12 +010016This 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
Eli Benderskyb6e66eb2013-11-28 06:53:05 -080022.. 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.
Antoine Pitrou31119e42013-11-22 17:38:12 +010037
Antoine Pitrou31119e42013-11-22 17:38:12 +010038.. 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
Eli Benderskyb6e66eb2013-11-28 06:53:05 -080099.. class:: PurePath(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100100
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800101 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
Antoine Pitrou8ad751e2015-04-12 00:08:02 +0200107 Each element of *pathsegments* can be either a string representing a
Brett Cannon568be632016-06-10 12:20:49 -0700108 path segment, an object implementing the :class:`os.PathLike` interface
109 which returns a string, or another path object::
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800110
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
Brett Cannon568be632016-06-10 12:20:49 -0700150 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
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800156.. class:: PurePosixPath(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100157
158 A subclass of :class:`PurePath`, this path flavour represents non-Windows
159 filesystem paths::
160
161 >>> PurePosixPath('/etc')
162 PurePosixPath('/etc')
163
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800164 *pathsegments* is specified similarly to :class:`PurePath`.
165
166.. class:: PureWindowsPath(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100167
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
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800174 *pathsegments* is specified similarly to :class:`PurePath`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100175
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
Antoine Pitrou31119e42013-11-22 17:38:12 +0100180General 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>
Victor Stinner91108f02015-10-14 18:25:31 +0200203 TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'
Antoine Pitrou31119e42013-11-22 17:38:12 +0100204
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
Brett Cannon568be632016-06-10 12:20:49 -0700220A 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
Antoine Pitrou31119e42013-11-22 17:38:12 +0100228The 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
Marco Buttu7b2491a2017-04-13 16:17:59 +0200274.. testsetup::
275
276 from pathlib import PurePosixPath, PureWindowsPath
277
Andrew Kuchling7a4e2d12013-11-22 15:45:02 -0500278Pure paths provide the following methods and properties:
Antoine Pitrou31119e42013-11-22 17:38:12 +0100279
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
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200467 With :class:`PureWindowsPath`, return ``True`` if the path is considered
468 reserved under Windows, ``False`` otherwise. With :class:`PurePosixPath`,
469 ``False`` is always returned.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100470
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
Andrew Kuchling7a4e2d12013-11-22 15:45:02 -0500482 Calling this method is equivalent to combining the path with each of
Antoine Pitrou31119e42013-11-22 17:38:12 +0100483 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
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200497 Match this path against the provided glob-style pattern. Return ``True``
498 if matching is successful, ``False`` otherwise.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100499
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
Antoine Pitrouef851192014-02-25 20:33:02 +0100542.. 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::
563
564 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
565 >>> p.with_suffix('.bz2')
566 PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
567 >>> p = PureWindowsPath('README')
568 >>> p.with_suffix('.txt')
569 PureWindowsPath('README.txt')
570
571
Antoine Pitrou31119e42013-11-22 17:38:12 +0100572.. _concrete-paths:
573
574
575Concrete paths
576--------------
577
578Concrete paths are subclasses of the pure path classes. In addition to
579operations provided by the latter, they also provide methods to do system
580calls on path objects. There are three ways to instantiate concrete paths:
581
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800582.. class:: Path(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100583
584 A subclass of :class:`PurePath`, this class represents concrete paths of
585 the system's path flavour (instantiating it creates either a
586 :class:`PosixPath` or a :class:`WindowsPath`)::
587
588 >>> Path('setup.py')
589 PosixPath('setup.py')
590
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800591 *pathsegments* is specified similarly to :class:`PurePath`.
592
593.. class:: PosixPath(*pathsegments)
594
595 A subclass of :class:`Path` and :class:`PurePosixPath`, this class
596 represents concrete non-Windows filesystem paths::
597
598 >>> PosixPath('/etc')
599 PosixPath('/etc')
600
601 *pathsegments* is specified similarly to :class:`PurePath`.
602
603.. class:: WindowsPath(*pathsegments)
604
605 A subclass of :class:`Path` and :class:`PureWindowsPath`, this class
606 represents concrete Windows filesystem paths::
607
608 >>> WindowsPath('c:/Program Files/')
609 WindowsPath('c:/Program Files')
610
611 *pathsegments* is specified similarly to :class:`PurePath`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100612
613You can only instantiate the class flavour that corresponds to your system
614(allowing system calls on non-compatible path flavours could lead to
615bugs or failures in your application)::
616
617 >>> import os
618 >>> os.name
619 'posix'
620 >>> Path('setup.py')
621 PosixPath('setup.py')
622 >>> PosixPath('setup.py')
623 PosixPath('setup.py')
624 >>> WindowsPath('setup.py')
625 Traceback (most recent call last):
626 File "<stdin>", line 1, in <module>
627 File "pathlib.py", line 798, in __new__
628 % (cls.__name__,))
629 NotImplementedError: cannot instantiate 'WindowsPath' on your system
630
631
632Methods
633^^^^^^^
634
635Concrete paths provide the following methods in addition to pure paths
636methods. Many of these methods can raise an :exc:`OSError` if a system
637call fails (for example because the path doesn't exist):
638
639.. classmethod:: Path.cwd()
640
641 Return a new path object representing the current directory (as returned
642 by :func:`os.getcwd`)::
643
644 >>> Path.cwd()
645 PosixPath('/home/antoine/pathlib')
646
647
Antoine Pitrou17cba7d2015-01-12 21:03:41 +0100648.. classmethod:: Path.home()
649
650 Return a new path object representing the user's home directory (as
651 returned by :func:`os.path.expanduser` with ``~`` construct)::
652
653 >>> Path.home()
654 PosixPath('/home/antoine')
655
656 .. versionadded:: 3.5
657
658
Antoine Pitrou31119e42013-11-22 17:38:12 +0100659.. method:: Path.stat()
660
661 Return information about this path (similarly to :func:`os.stat`).
662 The result is looked up at each call to this method.
663
Marco Buttu7b2491a2017-04-13 16:17:59 +0200664 ::
665
Antoine Pitrou31119e42013-11-22 17:38:12 +0100666 >>> p = Path('setup.py')
667 >>> p.stat().st_size
668 956
669 >>> p.stat().st_mtime
670 1327883547.852554
671
672
673.. method:: Path.chmod(mode)
674
675 Change the file mode and permissions, like :func:`os.chmod`::
676
677 >>> p = Path('setup.py')
678 >>> p.stat().st_mode
679 33277
680 >>> p.chmod(0o444)
681 >>> p.stat().st_mode
682 33060
683
684
685.. method:: Path.exists()
686
687 Whether the path points to an existing file or directory::
688
689 >>> Path('.').exists()
690 True
691 >>> Path('setup.py').exists()
692 True
693 >>> Path('/etc').exists()
694 True
695 >>> Path('nonexistentfile').exists()
696 False
697
698 .. note::
699 If the path points to a symlink, :meth:`exists` returns whether the
700 symlink *points to* an existing file or directory.
701
702
Antoine Pitrou8477ed62014-12-30 20:54:45 +0100703.. method:: Path.expanduser()
704
705 Return a new path with expanded ``~`` and ``~user`` constructs,
706 as returned by :meth:`os.path.expanduser`::
707
708 >>> p = PosixPath('~/films/Monty Python')
709 >>> p.expanduser()
710 PosixPath('/home/eric/films/Monty Python')
711
712 .. versionadded:: 3.5
713
714
Antoine Pitrou31119e42013-11-22 17:38:12 +0100715.. method:: Path.glob(pattern)
716
717 Glob the given *pattern* in the directory represented by this path,
718 yielding all matching files (of any kind)::
719
720 >>> sorted(Path('.').glob('*.py'))
721 [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
722 >>> sorted(Path('.').glob('*/*.py'))
723 [PosixPath('docs/conf.py')]
724
725 The "``**``" pattern means "this directory and all subdirectories,
726 recursively". In other words, it enables recursive globbing::
727
728 >>> sorted(Path('.').glob('**/*.py'))
729 [PosixPath('build/lib/pathlib.py'),
730 PosixPath('docs/conf.py'),
731 PosixPath('pathlib.py'),
732 PosixPath('setup.py'),
733 PosixPath('test_pathlib.py')]
734
735 .. note::
736 Using the "``**``" pattern in large directory trees may consume
737 an inordinate amount of time.
738
739
740.. method:: Path.group()
741
Ned Deilyc0341562013-11-27 14:42:55 -0800742 Return the name of the group owning the file. :exc:`KeyError` is raised
Antoine Pitrou31119e42013-11-22 17:38:12 +0100743 if the file's gid isn't found in the system database.
744
745
746.. method:: Path.is_dir()
747
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200748 Return ``True`` if the path points to a directory (or a symbolic link
749 pointing to a directory), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100750
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200751 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100752 other errors (such as permission errors) are propagated.
753
754
755.. method:: Path.is_file()
756
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200757 Return ``True`` if the path points to a regular file (or a symbolic link
758 pointing to a regular file), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100759
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200760 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100761 other errors (such as permission errors) are propagated.
762
763
764.. method:: Path.is_symlink()
765
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200766 Return ``True`` if the path points to a symbolic link, ``False`` otherwise.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100767
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200768 ``False`` is also returned if the path doesn't exist; other errors (such
Antoine Pitrou31119e42013-11-22 17:38:12 +0100769 as permission errors) are propagated.
770
771
772.. method:: Path.is_socket()
773
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200774 Return ``True`` if the path points to a Unix socket (or a symbolic link
775 pointing to a Unix socket), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100776
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200777 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100778 other errors (such as permission errors) are propagated.
779
780
781.. method:: Path.is_fifo()
782
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200783 Return ``True`` if the path points to a FIFO (or a symbolic link
784 pointing to a FIFO), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100785
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200786 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100787 other errors (such as permission errors) are propagated.
788
789
790.. method:: Path.is_block_device()
791
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200792 Return ``True`` if the path points to a block device (or a symbolic link
793 pointing to a block device), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100794
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200795 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100796 other errors (such as permission errors) are propagated.
797
798
799.. method:: Path.is_char_device()
800
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200801 Return ``True`` if the path points to a character device (or a symbolic link
802 pointing to a character device), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100803
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200804 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100805 other errors (such as permission errors) are propagated.
806
807
808.. method:: Path.iterdir()
809
810 When the path points to a directory, yield path objects of the directory
811 contents::
812
813 >>> p = Path('docs')
814 >>> for child in p.iterdir(): child
815 ...
816 PosixPath('docs/conf.py')
817 PosixPath('docs/_templates')
818 PosixPath('docs/make.bat')
819 PosixPath('docs/index.rst')
820 PosixPath('docs/_build')
821 PosixPath('docs/_static')
822 PosixPath('docs/Makefile')
823
824.. method:: Path.lchmod(mode)
825
826 Like :meth:`Path.chmod` but, if the path points to a symbolic link, the
827 symbolic link's mode is changed rather than its target's.
828
829
830.. method:: Path.lstat()
831
832 Like :meth:`Path.stat` but, if the path points to a symbolic link, return
833 the symbolic link's information rather than its target's.
834
835
Barry Warsaw7c549c42014-08-05 11:28:12 -0400836.. method:: Path.mkdir(mode=0o777, parents=False, exist_ok=False)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100837
838 Create a new directory at this given path. If *mode* is given, it is
839 combined with the process' ``umask`` value to determine the file mode
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100840 and access flags. If the path already exists, :exc:`FileExistsError`
841 is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100842
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200843 If *parents* is true, any missing parents of this path are created
Antoine Pitrou0048c982013-12-16 20:22:37 +0100844 as needed; they are created with the default permissions without taking
845 *mode* into account (mimicking the POSIX ``mkdir -p`` command).
846
847 If *parents* is false (the default), a missing parent raises
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100848 :exc:`FileNotFoundError`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100849
Ned Deily11194f72016-10-15 15:12:03 -0400850 If *exist_ok* is false (the default), :exc:`FileExistsError` is
Barry Warsaw7c549c42014-08-05 11:28:12 -0400851 raised if the target directory already exists.
852
853 If *exist_ok* is true, :exc:`FileExistsError` exceptions will be
854 ignored (same behavior as the POSIX ``mkdir -p`` command), but only if the
855 last path component is not an existing non-directory file.
856
857 .. versionchanged:: 3.5
858 The *exist_ok* parameter was added.
859
Antoine Pitrou31119e42013-11-22 17:38:12 +0100860
861.. method:: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
862
863 Open the file pointed to by the path, like the built-in :func:`open`
864 function does::
865
866 >>> p = Path('setup.py')
867 >>> with p.open() as f:
868 ... f.readline()
869 ...
870 '#!/usr/bin/env python3\n'
871
872
873.. method:: Path.owner()
874
Ned Deilyc0341562013-11-27 14:42:55 -0800875 Return the name of the user owning the file. :exc:`KeyError` is raised
Antoine Pitrou31119e42013-11-22 17:38:12 +0100876 if the file's uid isn't found in the system database.
877
878
Georg Brandlea683982014-10-01 19:12:33 +0200879.. method:: Path.read_bytes()
880
881 Return the binary contents of the pointed-to file as a bytes object::
882
883 >>> p = Path('my_binary_file')
884 >>> p.write_bytes(b'Binary file contents')
885 20
886 >>> p.read_bytes()
887 b'Binary file contents'
888
889 .. versionadded:: 3.5
890
891
892.. method:: Path.read_text(encoding=None, errors=None)
893
894 Return the decoded contents of the pointed-to file as a string::
895
896 >>> p = Path('my_text_file')
897 >>> p.write_text('Text file contents')
898 18
899 >>> p.read_text()
900 'Text file contents'
901
902 The optional parameters have the same meaning as in :func:`open`.
903
904 .. versionadded:: 3.5
905
906
Antoine Pitrou31119e42013-11-22 17:38:12 +0100907.. method:: Path.rename(target)
908
Berker Peksag2b879212016-07-14 07:44:59 +0300909 Rename this file or directory to the given *target*. On Unix, if
910 *target* exists and is a file, it will be replaced silently if the user
911 has permission. *target* can be either a string or another path object::
Antoine Pitrou31119e42013-11-22 17:38:12 +0100912
913 >>> p = Path('foo')
914 >>> p.open('w').write('some text')
915 9
916 >>> target = Path('bar')
917 >>> p.rename(target)
918 >>> target.open().read()
919 'some text'
920
921
922.. method:: Path.replace(target)
923
924 Rename this file or directory to the given *target*. If *target* points
925 to an existing file or directory, it will be unconditionally replaced.
926
927
Steve Dower98eb3602016-11-09 12:58:17 -0800928.. method:: Path.resolve(strict=False)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100929
930 Make the path absolute, resolving any symlinks. A new path object is
931 returned::
932
933 >>> p = Path()
934 >>> p
935 PosixPath('.')
936 >>> p.resolve()
937 PosixPath('/home/antoine/pathlib')
938
Berker Peksag5e3677d2016-10-01 01:06:52 +0300939 "``..``" components are also eliminated (this is the only method to do so)::
Antoine Pitrou31119e42013-11-22 17:38:12 +0100940
941 >>> p = Path('docs/../setup.py')
942 >>> p.resolve()
943 PosixPath('/home/antoine/pathlib/setup.py')
944
Steve Dower98eb3602016-11-09 12:58:17 -0800945 If the path doesn't exist and *strict* is ``True``, :exc:`FileNotFoundError`
946 is raised. If *strict* is ``False``, the path is resolved as far as possible
947 and any remainder is appended without checking whether it exists. If an
948 infinite loop is encountered along the resolution path, :exc:`RuntimeError`
949 is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100950
Steve Dower98eb3602016-11-09 12:58:17 -0800951 .. versionadded:: 3.6
952 The *strict* argument.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100953
954.. method:: Path.rglob(pattern)
955
Berker Peksag06a8ac02016-10-01 01:02:39 +0300956 This is like calling :meth:`Path.glob` with "``**``" added in front of the
Marco Buttu7b2491a2017-04-13 16:17:59 +0200957 given *pattern*::
Antoine Pitrou31119e42013-11-22 17:38:12 +0100958
959 >>> sorted(Path().rglob("*.py"))
960 [PosixPath('build/lib/pathlib.py'),
961 PosixPath('docs/conf.py'),
962 PosixPath('pathlib.py'),
963 PosixPath('setup.py'),
964 PosixPath('test_pathlib.py')]
965
966
967.. method:: Path.rmdir()
968
969 Remove this directory. The directory must be empty.
970
971
Antoine Pitrou43e3d942014-05-13 10:50:15 +0200972.. method:: Path.samefile(other_path)
973
974 Return whether this path points to the same file as *other_path*, which
975 can be either a Path object, or a string. The semantics are similar
976 to :func:`os.path.samefile` and :func:`os.path.samestat`.
977
978 An :exc:`OSError` can be raised if either file cannot be accessed for some
979 reason.
980
Marco Buttu7b2491a2017-04-13 16:17:59 +0200981 ::
982
Antoine Pitrou43e3d942014-05-13 10:50:15 +0200983 >>> p = Path('spam')
984 >>> q = Path('eggs')
985 >>> p.samefile(q)
986 False
987 >>> p.samefile('spam')
988 True
989
990 .. versionadded:: 3.5
991
992
Antoine Pitrou31119e42013-11-22 17:38:12 +0100993.. method:: Path.symlink_to(target, target_is_directory=False)
994
995 Make this path a symbolic link to *target*. Under Windows,
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200996 *target_is_directory* must be true (default ``False``) if the link's target
Antoine Pitrou31119e42013-11-22 17:38:12 +0100997 is a directory. Under POSIX, *target_is_directory*'s value is ignored.
998
Marco Buttu7b2491a2017-04-13 16:17:59 +0200999 ::
1000
Antoine Pitrou31119e42013-11-22 17:38:12 +01001001 >>> p = Path('mylink')
1002 >>> p.symlink_to('setup.py')
1003 >>> p.resolve()
1004 PosixPath('/home/antoine/pathlib/setup.py')
1005 >>> p.stat().st_size
1006 956
1007 >>> p.lstat().st_size
1008 8
1009
1010 .. note::
1011 The order of arguments (link, target) is the reverse
1012 of :func:`os.symlink`'s.
1013
1014
Zachary Ware7a26da52016-08-09 17:10:39 -05001015.. method:: Path.touch(mode=0o666, exist_ok=True)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001016
1017 Create a file at this given path. If *mode* is given, it is combined
1018 with the process' ``umask`` value to determine the file mode and access
1019 flags. If the file already exists, the function succeeds if *exist_ok*
1020 is true (and its modification time is updated to the current time),
Antoine Pitrouf6abb702013-12-16 21:00:53 +01001021 otherwise :exc:`FileExistsError` is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001022
1023
1024.. method:: Path.unlink()
1025
1026 Remove this file or symbolic link. If the path points to a directory,
1027 use :func:`Path.rmdir` instead.
Georg Brandlea683982014-10-01 19:12:33 +02001028
1029
1030.. method:: Path.write_bytes(data)
1031
1032 Open the file pointed to in bytes mode, write *data* to it, and close the
1033 file::
1034
1035 >>> p = Path('my_binary_file')
1036 >>> p.write_bytes(b'Binary file contents')
1037 20
1038 >>> p.read_bytes()
1039 b'Binary file contents'
1040
1041 An existing file of the same name is overwritten.
1042
1043 .. versionadded:: 3.5
1044
1045
1046.. method:: Path.write_text(data, encoding=None, errors=None)
1047
1048 Open the file pointed to in text mode, write *data* to it, and close the
1049 file::
1050
1051 >>> p = Path('my_text_file')
1052 >>> p.write_text('Text file contents')
1053 18
1054 >>> p.read_text()
1055 'Text file contents'
1056
Georg Brandlea683982014-10-01 19:12:33 +02001057 .. versionadded:: 3.5
Jamiel Almeidaae8750b2017-06-02 11:36:02 -07001058
1059Correspondence to tools in the :mod:`os` module
1060-----------------------------------------------
1061
1062Below is a table mapping various :mod:`os` functions to their corresponding
1063:class:`PurePath`/:class:`Path` equivalent.
1064
1065.. note::
1066
1067 Although :func:`os.path.relpath` and :meth:`PurePath.relative_to` have some
1068 overlapping use-cases, their semantics differ enough to warrant not
1069 considering them equivalent.
1070
1071============================ ==============================
1072os and os.path pathlib
1073============================ ==============================
1074:func:`os.path.abspath` :meth:`Path.resolve`
1075:func:`os.getcwd` :func:`Path.cwd`
1076:func:`os.path.exists` :meth:`Path.exists`
1077:func:`os.path.expanduser` :meth:`Path.expanduser` and
1078 :meth:`Path.home`
1079:func:`os.path.isdir` :meth:`Path.is_dir`
1080:func:`os.path.isfile` :meth:`Path.is_file`
1081:func:`os.path.islink` :meth:`Path.is_symlink`
1082:func:`os.stat` :meth:`Path.stat`,
1083 :meth:`Path.owner`,
1084 :meth:`Path.group`
1085:func:`os.path.isabs` :meth:`PurePath.is_absolute`
1086:func:`os.path.join` :func:`PurePath.joinpath`
1087:func:`os.path.basename` :data:`PurePath.name`
1088:func:`os.path.dirname` :data:`PurePath.parent`
1089:func:`os.path.splitext` :data:`PurePath.suffix`
1090============================ ==============================