blob: ff5196de86002fbcf81ef75963ae013a5d1d91f0 [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
8.. index:: single: path; operations
9
10.. versionadded:: 3.4
11
Antoine Pitrou31119e42013-11-22 17:38:12 +010012This module offers classes representing filesystem paths with semantics
13appropriate for different operating systems. Path classes are divided
14between :ref:`pure paths <pure-paths>`, which provide purely computational
15operations without I/O, and :ref:`concrete paths <concrete-paths>`, which
16inherit from pure paths but also provide I/O operations.
17
Eli Benderskyb6e66eb2013-11-28 06:53:05 -080018.. image:: pathlib-inheritance.png
19 :align: center
20
21If you've never used this module before or just aren't sure which class is
22right for your task, :class:`Path` is most likely what you need. It instantiates
23a :ref:`concrete path <concrete-paths>` for the platform the code is running on.
24
25Pure paths are useful in some special cases; for example:
26
27#. If you want to manipulate Windows paths on a Unix machine (or vice versa).
28 You cannot instantiate a :class:`WindowsPath` when running on Unix, but you
29 can instantiate :class:`PureWindowsPath`.
30#. You want to make sure that your code only manipulates paths without actually
31 accessing the OS. In this case, instantiating one of the pure classes may be
32 useful since those simply don't have any OS-accessing operations.
Antoine Pitrou31119e42013-11-22 17:38:12 +010033
34.. note::
Andrew Kuchling7a4e2d12013-11-22 15:45:02 -050035 This module has been included in the standard library on a
Antoine Pitrou31119e42013-11-22 17:38:12 +010036 :term:`provisional basis <provisional package>`. Backwards incompatible
37 changes (up to and including removal of the package) may occur if deemed
38 necessary by the core developers.
39
40.. seealso::
41 :pep:`428`: The pathlib module -- object-oriented filesystem paths.
42
43.. seealso::
44 For low-level path manipulation on strings, you can also use the
45 :mod:`os.path` module.
46
47
48Basic use
49---------
50
51Importing the main class::
52
53 >>> from pathlib import Path
54
55Listing subdirectories::
56
57 >>> p = Path('.')
58 >>> [x for x in p.iterdir() if x.is_dir()]
59 [PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
60 PosixPath('__pycache__'), PosixPath('build')]
61
62Listing Python source files in this directory tree::
63
64 >>> list(p.glob('**/*.py'))
65 [PosixPath('test_pathlib.py'), PosixPath('setup.py'),
66 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
67 PosixPath('build/lib/pathlib.py')]
68
69Navigating inside a directory tree::
70
71 >>> p = Path('/etc')
72 >>> q = p / 'init.d' / 'reboot'
73 >>> q
74 PosixPath('/etc/init.d/reboot')
75 >>> q.resolve()
76 PosixPath('/etc/rc.d/init.d/halt')
77
78Querying path properties::
79
80 >>> q.exists()
81 True
82 >>> q.is_dir()
83 False
84
85Opening a file::
86
87 >>> with q.open() as f: f.readline()
88 ...
89 '#!/bin/bash\n'
90
91
92.. _pure-paths:
93
94Pure paths
95----------
96
97Pure path objects provide path-handling operations which don't actually
98access a filesystem. There are three ways to access these classes, which
99we also call *flavours*:
100
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800101.. class:: PurePath(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100102
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800103 A generic class that represents the system's path flavour (instantiating
104 it creates either a :class:`PurePosixPath` or a :class:`PureWindowsPath`)::
105
106 >>> PurePath('setup.py') # Running on a Unix machine
107 PurePosixPath('setup.py')
108
Antoine Pitrou8ad751e2015-04-12 00:08:02 +0200109 Each element of *pathsegments* can be either a string representing a
110 path segment, or another path object::
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800111
112 >>> PurePath('foo', 'some/path', 'bar')
113 PurePosixPath('foo/some/path/bar')
114 >>> PurePath(Path('foo'), Path('bar'))
115 PurePosixPath('foo/bar')
116
117 When *pathsegments* is empty, the current directory is assumed::
118
119 >>> PurePath()
120 PurePosixPath('.')
121
122 When several absolute paths are given, the last is taken as an anchor
123 (mimicking :func:`os.path.join`'s behaviour)::
124
125 >>> PurePath('/etc', '/usr', 'lib64')
126 PurePosixPath('/usr/lib64')
127 >>> PureWindowsPath('c:/Windows', 'd:bar')
128 PureWindowsPath('d:bar')
129
130 However, in a Windows path, changing the local root doesn't discard the
131 previous drive setting::
132
133 >>> PureWindowsPath('c:/Windows', '/Program Files')
134 PureWindowsPath('c:/Program Files')
135
136 Spurious slashes and single dots are collapsed, but double dots (``'..'``)
137 are not, since this would change the meaning of a path in the face of
138 symbolic links::
139
140 >>> PurePath('foo//bar')
141 PurePosixPath('foo/bar')
142 >>> PurePath('foo/./bar')
143 PurePosixPath('foo/bar')
144 >>> PurePath('foo/../bar')
145 PurePosixPath('foo/../bar')
146
147 (a naïve approach would make ``PurePosixPath('foo/../bar')`` equivalent
148 to ``PurePosixPath('bar')``, which is wrong if ``foo`` is a symbolic link
149 to another directory)
150
151.. class:: PurePosixPath(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100152
153 A subclass of :class:`PurePath`, this path flavour represents non-Windows
154 filesystem paths::
155
156 >>> PurePosixPath('/etc')
157 PurePosixPath('/etc')
158
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800159 *pathsegments* is specified similarly to :class:`PurePath`.
160
161.. class:: PureWindowsPath(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100162
163 A subclass of :class:`PurePath`, this path flavour represents Windows
164 filesystem paths::
165
166 >>> PureWindowsPath('c:/Program Files/')
167 PureWindowsPath('c:/Program Files')
168
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800169 *pathsegments* is specified similarly to :class:`PurePath`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100170
171Regardless of the system you're running on, you can instantiate all of
172these classes, since they don't provide any operation that does system calls.
173
174
Antoine Pitrou31119e42013-11-22 17:38:12 +0100175General properties
176^^^^^^^^^^^^^^^^^^
177
178Paths are immutable and hashable. Paths of a same flavour are comparable
179and orderable. These properties respect the flavour's case-folding
180semantics::
181
182 >>> PurePosixPath('foo') == PurePosixPath('FOO')
183 False
184 >>> PureWindowsPath('foo') == PureWindowsPath('FOO')
185 True
186 >>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
187 True
188 >>> PureWindowsPath('C:') < PureWindowsPath('d:')
189 True
190
191Paths of a different flavour compare unequal and cannot be ordered::
192
193 >>> PureWindowsPath('foo') == PurePosixPath('foo')
194 False
195 >>> PureWindowsPath('foo') < PurePosixPath('foo')
196 Traceback (most recent call last):
197 File "<stdin>", line 1, in <module>
Victor Stinner91108f02015-10-14 18:25:31 +0200198 TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'
Antoine Pitrou31119e42013-11-22 17:38:12 +0100199
200
201Operators
202^^^^^^^^^
203
204The slash operator helps create child paths, similarly to :func:`os.path.join`::
205
206 >>> p = PurePath('/etc')
207 >>> p
208 PurePosixPath('/etc')
209 >>> p / 'init.d' / 'apache2'
210 PurePosixPath('/etc/init.d/apache2')
211 >>> q = PurePath('bin')
212 >>> '/usr' / q
213 PurePosixPath('/usr/bin')
214
215The string representation of a path is the raw filesystem path itself
216(in native form, e.g. with backslashes under Windows), which you can
217pass to any function taking a file path as a string::
218
219 >>> p = PurePath('/etc')
220 >>> str(p)
221 '/etc'
222 >>> p = PureWindowsPath('c:/Program Files')
223 >>> str(p)
224 'c:\\Program Files'
225
226Similarly, calling :class:`bytes` on a path gives the raw filesystem path as a
227bytes object, as encoded by :func:`os.fsencode`::
228
229 >>> bytes(p)
230 b'/etc'
231
232.. note::
233 Calling :class:`bytes` is only recommended under Unix. Under Windows,
234 the unicode form is the canonical representation of filesystem paths.
235
236
237Accessing individual parts
238^^^^^^^^^^^^^^^^^^^^^^^^^^
239
240To access the individual "parts" (components) of a path, use the following
241property:
242
243.. data:: PurePath.parts
244
245 A tuple giving access to the path's various components::
246
247 >>> p = PurePath('/usr/bin/python3')
248 >>> p.parts
249 ('/', 'usr', 'bin', 'python3')
250
251 >>> p = PureWindowsPath('c:/Program Files/PSF')
252 >>> p.parts
253 ('c:\\', 'Program Files', 'PSF')
254
255 (note how the drive and local root are regrouped in a single part)
256
257
258Methods and properties
259^^^^^^^^^^^^^^^^^^^^^^
260
Andrew Kuchling7a4e2d12013-11-22 15:45:02 -0500261Pure paths provide the following methods and properties:
Antoine Pitrou31119e42013-11-22 17:38:12 +0100262
263.. data:: PurePath.drive
264
265 A string representing the drive letter or name, if any::
266
267 >>> PureWindowsPath('c:/Program Files/').drive
268 'c:'
269 >>> PureWindowsPath('/Program Files/').drive
270 ''
271 >>> PurePosixPath('/etc').drive
272 ''
273
274 UNC shares are also considered drives::
275
276 >>> PureWindowsPath('//host/share/foo.txt').drive
277 '\\\\host\\share'
278
279.. data:: PurePath.root
280
281 A string representing the (local or global) root, if any::
282
283 >>> PureWindowsPath('c:/Program Files/').root
284 '\\'
285 >>> PureWindowsPath('c:Program Files/').root
286 ''
287 >>> PurePosixPath('/etc').root
288 '/'
289
290 UNC shares always have a root::
291
292 >>> PureWindowsPath('//host/share').root
293 '\\'
294
295.. data:: PurePath.anchor
296
297 The concatenation of the drive and root::
298
299 >>> PureWindowsPath('c:/Program Files/').anchor
300 'c:\\'
301 >>> PureWindowsPath('c:Program Files/').anchor
302 'c:'
303 >>> PurePosixPath('/etc').anchor
304 '/'
305 >>> PureWindowsPath('//host/share').anchor
306 '\\\\host\\share\\'
307
308
309.. data:: PurePath.parents
310
311 An immutable sequence providing access to the logical ancestors of
312 the path::
313
314 >>> p = PureWindowsPath('c:/foo/bar/setup.py')
315 >>> p.parents[0]
316 PureWindowsPath('c:/foo/bar')
317 >>> p.parents[1]
318 PureWindowsPath('c:/foo')
319 >>> p.parents[2]
320 PureWindowsPath('c:/')
321
322
323.. data:: PurePath.parent
324
325 The logical parent of the path::
326
327 >>> p = PurePosixPath('/a/b/c/d')
328 >>> p.parent
329 PurePosixPath('/a/b/c')
330
331 You cannot go past an anchor, or empty path::
332
333 >>> p = PurePosixPath('/')
334 >>> p.parent
335 PurePosixPath('/')
336 >>> p = PurePosixPath('.')
337 >>> p.parent
338 PurePosixPath('.')
339
340 .. note::
341 This is a purely lexical operation, hence the following behaviour::
342
343 >>> p = PurePosixPath('foo/..')
344 >>> p.parent
345 PurePosixPath('foo')
346
347 If you want to walk an arbitrary filesystem path upwards, it is
348 recommended to first call :meth:`Path.resolve` so as to resolve
349 symlinks and eliminate `".."` components.
350
351
352.. data:: PurePath.name
353
354 A string representing the final path component, excluding the drive and
355 root, if any::
356
357 >>> PurePosixPath('my/library/setup.py').name
358 'setup.py'
359
360 UNC drive names are not considered::
361
362 >>> PureWindowsPath('//some/share/setup.py').name
363 'setup.py'
364 >>> PureWindowsPath('//some/share').name
365 ''
366
367
368.. data:: PurePath.suffix
369
370 The file extension of the final component, if any::
371
372 >>> PurePosixPath('my/library/setup.py').suffix
373 '.py'
374 >>> PurePosixPath('my/library.tar.gz').suffix
375 '.gz'
376 >>> PurePosixPath('my/library').suffix
377 ''
378
379
380.. data:: PurePath.suffixes
381
382 A list of the path's file extensions::
383
384 >>> PurePosixPath('my/library.tar.gar').suffixes
385 ['.tar', '.gar']
386 >>> PurePosixPath('my/library.tar.gz').suffixes
387 ['.tar', '.gz']
388 >>> PurePosixPath('my/library').suffixes
389 []
390
391
392.. data:: PurePath.stem
393
394 The final path component, without its suffix::
395
396 >>> PurePosixPath('my/library.tar.gz').stem
397 'library.tar'
398 >>> PurePosixPath('my/library.tar').stem
399 'library'
400 >>> PurePosixPath('my/library').stem
401 'library'
402
403
404.. method:: PurePath.as_posix()
405
406 Return a string representation of the path with forward slashes (``/``)::
407
408 >>> p = PureWindowsPath('c:\\windows')
409 >>> str(p)
410 'c:\\windows'
411 >>> p.as_posix()
412 'c:/windows'
413
414
415.. method:: PurePath.as_uri()
416
417 Represent the path as a ``file`` URI. :exc:`ValueError` is raised if
418 the path isn't absolute.
419
420 >>> p = PurePosixPath('/etc/passwd')
421 >>> p.as_uri()
422 'file:///etc/passwd'
423 >>> p = PureWindowsPath('c:/Windows')
424 >>> p.as_uri()
425 'file:///c:/Windows'
426
427
428.. method:: PurePath.is_absolute()
429
430 Return whether the path is absolute or not. A path is considered absolute
431 if it has both a root and (if the flavour allows) a drive::
432
433 >>> PurePosixPath('/a/b').is_absolute()
434 True
435 >>> PurePosixPath('a/b').is_absolute()
436 False
437
438 >>> PureWindowsPath('c:/a/b').is_absolute()
439 True
440 >>> PureWindowsPath('/a/b').is_absolute()
441 False
442 >>> PureWindowsPath('c:').is_absolute()
443 False
444 >>> PureWindowsPath('//some/share').is_absolute()
445 True
446
447
448.. method:: PurePath.is_reserved()
449
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200450 With :class:`PureWindowsPath`, return ``True`` if the path is considered
451 reserved under Windows, ``False`` otherwise. With :class:`PurePosixPath`,
452 ``False`` is always returned.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100453
454 >>> PureWindowsPath('nul').is_reserved()
455 True
456 >>> PurePosixPath('nul').is_reserved()
457 False
458
459 File system calls on reserved paths can fail mysteriously or have
460 unintended effects.
461
462
463.. method:: PurePath.joinpath(*other)
464
Andrew Kuchling7a4e2d12013-11-22 15:45:02 -0500465 Calling this method is equivalent to combining the path with each of
Antoine Pitrou31119e42013-11-22 17:38:12 +0100466 the *other* arguments in turn::
467
468 >>> PurePosixPath('/etc').joinpath('passwd')
469 PurePosixPath('/etc/passwd')
470 >>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
471 PurePosixPath('/etc/passwd')
472 >>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
473 PurePosixPath('/etc/init.d/apache2')
474 >>> PureWindowsPath('c:').joinpath('/Program Files')
475 PureWindowsPath('c:/Program Files')
476
477
478.. method:: PurePath.match(pattern)
479
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200480 Match this path against the provided glob-style pattern. Return ``True``
481 if matching is successful, ``False`` otherwise.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100482
483 If *pattern* is relative, the path can be either relative or absolute,
484 and matching is done from the right::
485
486 >>> PurePath('a/b.py').match('*.py')
487 True
488 >>> PurePath('/a/b/c.py').match('b/*.py')
489 True
490 >>> PurePath('/a/b/c.py').match('a/*.py')
491 False
492
493 If *pattern* is absolute, the path must be absolute, and the whole path
494 must match::
495
496 >>> PurePath('/a.py').match('/*.py')
497 True
498 >>> PurePath('a/b.py').match('/*.py')
499 False
500
501 As with other methods, case-sensitivity is observed::
502
503 >>> PureWindowsPath('b.py').match('*.PY')
504 True
505
506
507.. method:: PurePath.relative_to(*other)
508
509 Compute a version of this path relative to the path represented by
510 *other*. If it's impossible, ValueError is raised::
511
512 >>> p = PurePosixPath('/etc/passwd')
513 >>> p.relative_to('/')
514 PurePosixPath('etc/passwd')
515 >>> p.relative_to('/etc')
516 PurePosixPath('passwd')
517 >>> p.relative_to('/usr')
518 Traceback (most recent call last):
519 File "<stdin>", line 1, in <module>
520 File "pathlib.py", line 694, in relative_to
521 .format(str(self), str(formatted)))
522 ValueError: '/etc/passwd' does not start with '/usr'
523
524
Antoine Pitrouef851192014-02-25 20:33:02 +0100525.. method:: PurePath.with_name(name)
526
527 Return a new path with the :attr:`name` changed. If the original path
528 doesn't have a name, ValueError is raised::
529
530 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
531 >>> p.with_name('setup.py')
532 PureWindowsPath('c:/Downloads/setup.py')
533 >>> p = PureWindowsPath('c:/')
534 >>> p.with_name('setup.py')
535 Traceback (most recent call last):
536 File "<stdin>", line 1, in <module>
537 File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
538 raise ValueError("%r has an empty name" % (self,))
539 ValueError: PureWindowsPath('c:/') has an empty name
540
541
542.. method:: PurePath.with_suffix(suffix)
543
544 Return a new path with the :attr:`suffix` changed. If the original path
545 doesn't have a suffix, the new *suffix* is appended instead::
546
547 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
548 >>> p.with_suffix('.bz2')
549 PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
550 >>> p = PureWindowsPath('README')
551 >>> p.with_suffix('.txt')
552 PureWindowsPath('README.txt')
553
554
Antoine Pitrou31119e42013-11-22 17:38:12 +0100555.. _concrete-paths:
556
557
558Concrete paths
559--------------
560
561Concrete paths are subclasses of the pure path classes. In addition to
562operations provided by the latter, they also provide methods to do system
563calls on path objects. There are three ways to instantiate concrete paths:
564
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800565.. class:: Path(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100566
567 A subclass of :class:`PurePath`, this class represents concrete paths of
568 the system's path flavour (instantiating it creates either a
569 :class:`PosixPath` or a :class:`WindowsPath`)::
570
571 >>> Path('setup.py')
572 PosixPath('setup.py')
573
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800574 *pathsegments* is specified similarly to :class:`PurePath`.
575
576.. class:: PosixPath(*pathsegments)
577
578 A subclass of :class:`Path` and :class:`PurePosixPath`, this class
579 represents concrete non-Windows filesystem paths::
580
581 >>> PosixPath('/etc')
582 PosixPath('/etc')
583
584 *pathsegments* is specified similarly to :class:`PurePath`.
585
586.. class:: WindowsPath(*pathsegments)
587
588 A subclass of :class:`Path` and :class:`PureWindowsPath`, this class
589 represents concrete Windows filesystem paths::
590
591 >>> WindowsPath('c:/Program Files/')
592 WindowsPath('c:/Program Files')
593
594 *pathsegments* is specified similarly to :class:`PurePath`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100595
596You can only instantiate the class flavour that corresponds to your system
597(allowing system calls on non-compatible path flavours could lead to
598bugs or failures in your application)::
599
600 >>> import os
601 >>> os.name
602 'posix'
603 >>> Path('setup.py')
604 PosixPath('setup.py')
605 >>> PosixPath('setup.py')
606 PosixPath('setup.py')
607 >>> WindowsPath('setup.py')
608 Traceback (most recent call last):
609 File "<stdin>", line 1, in <module>
610 File "pathlib.py", line 798, in __new__
611 % (cls.__name__,))
612 NotImplementedError: cannot instantiate 'WindowsPath' on your system
613
614
615Methods
616^^^^^^^
617
618Concrete paths provide the following methods in addition to pure paths
619methods. Many of these methods can raise an :exc:`OSError` if a system
620call fails (for example because the path doesn't exist):
621
622.. classmethod:: Path.cwd()
623
624 Return a new path object representing the current directory (as returned
625 by :func:`os.getcwd`)::
626
627 >>> Path.cwd()
628 PosixPath('/home/antoine/pathlib')
629
630
Antoine Pitrou17cba7d2015-01-12 21:03:41 +0100631.. classmethod:: Path.home()
632
633 Return a new path object representing the user's home directory (as
634 returned by :func:`os.path.expanduser` with ``~`` construct)::
635
636 >>> Path.home()
637 PosixPath('/home/antoine')
638
639 .. versionadded:: 3.5
640
641
Antoine Pitrou31119e42013-11-22 17:38:12 +0100642.. method:: Path.stat()
643
644 Return information about this path (similarly to :func:`os.stat`).
645 The result is looked up at each call to this method.
646
647 >>> p = Path('setup.py')
648 >>> p.stat().st_size
649 956
650 >>> p.stat().st_mtime
651 1327883547.852554
652
653
654.. method:: Path.chmod(mode)
655
656 Change the file mode and permissions, like :func:`os.chmod`::
657
658 >>> p = Path('setup.py')
659 >>> p.stat().st_mode
660 33277
661 >>> p.chmod(0o444)
662 >>> p.stat().st_mode
663 33060
664
665
666.. method:: Path.exists()
667
668 Whether the path points to an existing file or directory::
669
670 >>> Path('.').exists()
671 True
672 >>> Path('setup.py').exists()
673 True
674 >>> Path('/etc').exists()
675 True
676 >>> Path('nonexistentfile').exists()
677 False
678
679 .. note::
680 If the path points to a symlink, :meth:`exists` returns whether the
681 symlink *points to* an existing file or directory.
682
683
Antoine Pitrou8477ed62014-12-30 20:54:45 +0100684.. method:: Path.expanduser()
685
686 Return a new path with expanded ``~`` and ``~user`` constructs,
687 as returned by :meth:`os.path.expanduser`::
688
689 >>> p = PosixPath('~/films/Monty Python')
690 >>> p.expanduser()
691 PosixPath('/home/eric/films/Monty Python')
692
693 .. versionadded:: 3.5
694
695
Antoine Pitrou31119e42013-11-22 17:38:12 +0100696.. method:: Path.glob(pattern)
697
698 Glob the given *pattern* in the directory represented by this path,
699 yielding all matching files (of any kind)::
700
701 >>> sorted(Path('.').glob('*.py'))
702 [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
703 >>> sorted(Path('.').glob('*/*.py'))
704 [PosixPath('docs/conf.py')]
705
706 The "``**``" pattern means "this directory and all subdirectories,
707 recursively". In other words, it enables recursive globbing::
708
709 >>> sorted(Path('.').glob('**/*.py'))
710 [PosixPath('build/lib/pathlib.py'),
711 PosixPath('docs/conf.py'),
712 PosixPath('pathlib.py'),
713 PosixPath('setup.py'),
714 PosixPath('test_pathlib.py')]
715
716 .. note::
717 Using the "``**``" pattern in large directory trees may consume
718 an inordinate amount of time.
719
720
721.. method:: Path.group()
722
Ned Deilyc0341562013-11-27 14:42:55 -0800723 Return the name of the group owning the file. :exc:`KeyError` is raised
Antoine Pitrou31119e42013-11-22 17:38:12 +0100724 if the file's gid isn't found in the system database.
725
726
727.. method:: Path.is_dir()
728
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200729 Return ``True`` if the path points to a directory (or a symbolic link
730 pointing to a directory), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100731
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200732 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100733 other errors (such as permission errors) are propagated.
734
735
736.. method:: Path.is_file()
737
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200738 Return ``True`` if the path points to a regular file (or a symbolic link
739 pointing to a regular file), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100740
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200741 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100742 other errors (such as permission errors) are propagated.
743
744
745.. method:: Path.is_symlink()
746
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200747 Return ``True`` if the path points to a symbolic link, ``False`` otherwise.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100748
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200749 ``False`` is also returned if the path doesn't exist; other errors (such
Antoine Pitrou31119e42013-11-22 17:38:12 +0100750 as permission errors) are propagated.
751
752
753.. method:: Path.is_socket()
754
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200755 Return ``True`` if the path points to a Unix socket (or a symbolic link
756 pointing to a Unix socket), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100757
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200758 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100759 other errors (such as permission errors) are propagated.
760
761
762.. method:: Path.is_fifo()
763
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200764 Return ``True`` if the path points to a FIFO (or a symbolic link
765 pointing to a FIFO), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100766
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200767 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100768 other errors (such as permission errors) are propagated.
769
770
771.. method:: Path.is_block_device()
772
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200773 Return ``True`` if the path points to a block device (or a symbolic link
774 pointing to a block device), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100775
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200776 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100777 other errors (such as permission errors) are propagated.
778
779
780.. method:: Path.is_char_device()
781
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200782 Return ``True`` if the path points to a character device (or a symbolic link
783 pointing to a character device), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100784
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200785 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100786 other errors (such as permission errors) are propagated.
787
788
789.. method:: Path.iterdir()
790
791 When the path points to a directory, yield path objects of the directory
792 contents::
793
794 >>> p = Path('docs')
795 >>> for child in p.iterdir(): child
796 ...
797 PosixPath('docs/conf.py')
798 PosixPath('docs/_templates')
799 PosixPath('docs/make.bat')
800 PosixPath('docs/index.rst')
801 PosixPath('docs/_build')
802 PosixPath('docs/_static')
803 PosixPath('docs/Makefile')
804
805.. method:: Path.lchmod(mode)
806
807 Like :meth:`Path.chmod` but, if the path points to a symbolic link, the
808 symbolic link's mode is changed rather than its target's.
809
810
811.. method:: Path.lstat()
812
813 Like :meth:`Path.stat` but, if the path points to a symbolic link, return
814 the symbolic link's information rather than its target's.
815
816
Barry Warsaw7c549c42014-08-05 11:28:12 -0400817.. method:: Path.mkdir(mode=0o777, parents=False, exist_ok=False)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100818
819 Create a new directory at this given path. If *mode* is given, it is
820 combined with the process' ``umask`` value to determine the file mode
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100821 and access flags. If the path already exists, :exc:`FileExistsError`
822 is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100823
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200824 If *parents* is true, any missing parents of this path are created
Antoine Pitrou0048c982013-12-16 20:22:37 +0100825 as needed; they are created with the default permissions without taking
826 *mode* into account (mimicking the POSIX ``mkdir -p`` command).
827
828 If *parents* is false (the default), a missing parent raises
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100829 :exc:`FileNotFoundError`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100830
Barry Warsaw7c549c42014-08-05 11:28:12 -0400831 If *exist_ok* is false (the default), an :exc:`FileExistsError` is
832 raised if the target directory already exists.
833
834 If *exist_ok* is true, :exc:`FileExistsError` exceptions will be
835 ignored (same behavior as the POSIX ``mkdir -p`` command), but only if the
836 last path component is not an existing non-directory file.
837
838 .. versionchanged:: 3.5
839 The *exist_ok* parameter was added.
840
Antoine Pitrou31119e42013-11-22 17:38:12 +0100841
842.. method:: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
843
844 Open the file pointed to by the path, like the built-in :func:`open`
845 function does::
846
847 >>> p = Path('setup.py')
848 >>> with p.open() as f:
849 ... f.readline()
850 ...
851 '#!/usr/bin/env python3\n'
852
853
854.. method:: Path.owner()
855
Ned Deilyc0341562013-11-27 14:42:55 -0800856 Return the name of the user owning the file. :exc:`KeyError` is raised
Antoine Pitrou31119e42013-11-22 17:38:12 +0100857 if the file's uid isn't found in the system database.
858
859
Georg Brandlea683982014-10-01 19:12:33 +0200860.. method:: Path.read_bytes()
861
862 Return the binary contents of the pointed-to file as a bytes object::
863
864 >>> p = Path('my_binary_file')
865 >>> p.write_bytes(b'Binary file contents')
866 20
867 >>> p.read_bytes()
868 b'Binary file contents'
869
870 .. versionadded:: 3.5
871
872
873.. method:: Path.read_text(encoding=None, errors=None)
874
875 Return the decoded contents of the pointed-to file as a string::
876
877 >>> p = Path('my_text_file')
878 >>> p.write_text('Text file contents')
879 18
880 >>> p.read_text()
881 'Text file contents'
882
883 The optional parameters have the same meaning as in :func:`open`.
884
885 .. versionadded:: 3.5
886
887
Antoine Pitrou31119e42013-11-22 17:38:12 +0100888.. method:: Path.rename(target)
889
890 Rename this file or directory to the given *target*. *target* can be
891 either a string or another path object::
892
893 >>> p = Path('foo')
894 >>> p.open('w').write('some text')
895 9
896 >>> target = Path('bar')
897 >>> p.rename(target)
898 >>> target.open().read()
899 'some text'
900
901
902.. method:: Path.replace(target)
903
904 Rename this file or directory to the given *target*. If *target* points
905 to an existing file or directory, it will be unconditionally replaced.
906
907
908.. method:: Path.resolve()
909
910 Make the path absolute, resolving any symlinks. A new path object is
911 returned::
912
913 >>> p = Path()
914 >>> p
915 PosixPath('.')
916 >>> p.resolve()
917 PosixPath('/home/antoine/pathlib')
918
919 `".."` components are also eliminated (this is the only method to do so)::
920
921 >>> p = Path('docs/../setup.py')
922 >>> p.resolve()
923 PosixPath('/home/antoine/pathlib/setup.py')
924
925 If the path doesn't exist, :exc:`FileNotFoundError` is raised. If an
926 infinite loop is encountered along the resolution path,
927 :exc:`RuntimeError` is raised.
928
929
930.. method:: Path.rglob(pattern)
931
932 This is like calling :meth:`glob` with "``**``" added in front of the
933 given *pattern*:
934
935 >>> sorted(Path().rglob("*.py"))
936 [PosixPath('build/lib/pathlib.py'),
937 PosixPath('docs/conf.py'),
938 PosixPath('pathlib.py'),
939 PosixPath('setup.py'),
940 PosixPath('test_pathlib.py')]
941
942
943.. method:: Path.rmdir()
944
945 Remove this directory. The directory must be empty.
946
947
Antoine Pitrou43e3d942014-05-13 10:50:15 +0200948.. method:: Path.samefile(other_path)
949
950 Return whether this path points to the same file as *other_path*, which
951 can be either a Path object, or a string. The semantics are similar
952 to :func:`os.path.samefile` and :func:`os.path.samestat`.
953
954 An :exc:`OSError` can be raised if either file cannot be accessed for some
955 reason.
956
957 >>> p = Path('spam')
958 >>> q = Path('eggs')
959 >>> p.samefile(q)
960 False
961 >>> p.samefile('spam')
962 True
963
964 .. versionadded:: 3.5
965
966
Antoine Pitrou31119e42013-11-22 17:38:12 +0100967.. method:: Path.symlink_to(target, target_is_directory=False)
968
969 Make this path a symbolic link to *target*. Under Windows,
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200970 *target_is_directory* must be true (default ``False``) if the link's target
Antoine Pitrou31119e42013-11-22 17:38:12 +0100971 is a directory. Under POSIX, *target_is_directory*'s value is ignored.
972
973 >>> p = Path('mylink')
974 >>> p.symlink_to('setup.py')
975 >>> p.resolve()
976 PosixPath('/home/antoine/pathlib/setup.py')
977 >>> p.stat().st_size
978 956
979 >>> p.lstat().st_size
980 8
981
982 .. note::
983 The order of arguments (link, target) is the reverse
984 of :func:`os.symlink`'s.
985
986
987.. method:: Path.touch(mode=0o777, exist_ok=True)
988
989 Create a file at this given path. If *mode* is given, it is combined
990 with the process' ``umask`` value to determine the file mode and access
991 flags. If the file already exists, the function succeeds if *exist_ok*
992 is true (and its modification time is updated to the current time),
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100993 otherwise :exc:`FileExistsError` is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100994
995
996.. method:: Path.unlink()
997
998 Remove this file or symbolic link. If the path points to a directory,
999 use :func:`Path.rmdir` instead.
Georg Brandlea683982014-10-01 19:12:33 +02001000
1001
1002.. method:: Path.write_bytes(data)
1003
1004 Open the file pointed to in bytes mode, write *data* to it, and close the
1005 file::
1006
1007 >>> p = Path('my_binary_file')
1008 >>> p.write_bytes(b'Binary file contents')
1009 20
1010 >>> p.read_bytes()
1011 b'Binary file contents'
1012
1013 An existing file of the same name is overwritten.
1014
1015 .. versionadded:: 3.5
1016
1017
1018.. method:: Path.write_text(data, encoding=None, errors=None)
1019
1020 Open the file pointed to in text mode, write *data* to it, and close the
1021 file::
1022
1023 >>> p = Path('my_text_file')
1024 >>> p.write_text('Text file contents')
1025 18
1026 >>> p.read_text()
1027 'Text file contents'
1028
Georg Brandlea683982014-10-01 19:12:33 +02001029 .. versionadded:: 3.5