blob: cb066bdc094e3b6227335a14dde2ddcb4f1f9d10 [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>
198 TypeError: unorderable types: PureWindowsPath() < PurePosixPath()
199
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
Guido van Rossumdf859462016-01-06 11:15:52 -0800368.. data:: PurePath.path
369
370 A string representing the full path::
371
372 >>> PurePosixPath('my/library/setup.py').path
373 'my/library/setup.py'
374
375 This always returns the same value as ``str(p)``; it is included to
376 serve as a one-off protocol. Code that wants to support both
377 strings and ``pathlib.Path`` objects as filenames can write
378 ``arg = getattr(arg, 'path', arg)`` to get the path as a string.
379 This can then be passed to various system calls or library
380 functions that expect a string. Unlike the alternative
381 ``arg = str(arg)``, this will still raise an exception if an object
382 of some other type is given by accident.
383
Guido van Rossumb1360542016-01-06 11:23:31 -0800384 .. versionadded:: 3.4.5
Guido van Rossumdf859462016-01-06 11:15:52 -0800385
Antoine Pitrou31119e42013-11-22 17:38:12 +0100386.. data:: PurePath.suffix
387
388 The file extension of the final component, if any::
389
390 >>> PurePosixPath('my/library/setup.py').suffix
391 '.py'
392 >>> PurePosixPath('my/library.tar.gz').suffix
393 '.gz'
394 >>> PurePosixPath('my/library').suffix
395 ''
396
397
398.. data:: PurePath.suffixes
399
400 A list of the path's file extensions::
401
402 >>> PurePosixPath('my/library.tar.gar').suffixes
403 ['.tar', '.gar']
404 >>> PurePosixPath('my/library.tar.gz').suffixes
405 ['.tar', '.gz']
406 >>> PurePosixPath('my/library').suffixes
407 []
408
409
410.. data:: PurePath.stem
411
412 The final path component, without its suffix::
413
414 >>> PurePosixPath('my/library.tar.gz').stem
415 'library.tar'
416 >>> PurePosixPath('my/library.tar').stem
417 'library'
418 >>> PurePosixPath('my/library').stem
419 'library'
420
421
422.. method:: PurePath.as_posix()
423
424 Return a string representation of the path with forward slashes (``/``)::
425
426 >>> p = PureWindowsPath('c:\\windows')
427 >>> str(p)
428 'c:\\windows'
429 >>> p.as_posix()
430 'c:/windows'
431
432
433.. method:: PurePath.as_uri()
434
435 Represent the path as a ``file`` URI. :exc:`ValueError` is raised if
436 the path isn't absolute.
437
438 >>> p = PurePosixPath('/etc/passwd')
439 >>> p.as_uri()
440 'file:///etc/passwd'
441 >>> p = PureWindowsPath('c:/Windows')
442 >>> p.as_uri()
443 'file:///c:/Windows'
444
445
446.. method:: PurePath.is_absolute()
447
448 Return whether the path is absolute or not. A path is considered absolute
449 if it has both a root and (if the flavour allows) a drive::
450
451 >>> PurePosixPath('/a/b').is_absolute()
452 True
453 >>> PurePosixPath('a/b').is_absolute()
454 False
455
456 >>> PureWindowsPath('c:/a/b').is_absolute()
457 True
458 >>> PureWindowsPath('/a/b').is_absolute()
459 False
460 >>> PureWindowsPath('c:').is_absolute()
461 False
462 >>> PureWindowsPath('//some/share').is_absolute()
463 True
464
465
466.. method:: PurePath.is_reserved()
467
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200468 With :class:`PureWindowsPath`, return ``True`` if the path is considered
469 reserved under Windows, ``False`` otherwise. With :class:`PurePosixPath`,
470 ``False`` is always returned.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100471
472 >>> PureWindowsPath('nul').is_reserved()
473 True
474 >>> PurePosixPath('nul').is_reserved()
475 False
476
477 File system calls on reserved paths can fail mysteriously or have
478 unintended effects.
479
480
481.. method:: PurePath.joinpath(*other)
482
Andrew Kuchling7a4e2d12013-11-22 15:45:02 -0500483 Calling this method is equivalent to combining the path with each of
Antoine Pitrou31119e42013-11-22 17:38:12 +0100484 the *other* arguments in turn::
485
486 >>> PurePosixPath('/etc').joinpath('passwd')
487 PurePosixPath('/etc/passwd')
488 >>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
489 PurePosixPath('/etc/passwd')
490 >>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
491 PurePosixPath('/etc/init.d/apache2')
492 >>> PureWindowsPath('c:').joinpath('/Program Files')
493 PureWindowsPath('c:/Program Files')
494
495
496.. method:: PurePath.match(pattern)
497
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200498 Match this path against the provided glob-style pattern. Return ``True``
499 if matching is successful, ``False`` otherwise.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100500
501 If *pattern* is relative, the path can be either relative or absolute,
502 and matching is done from the right::
503
504 >>> PurePath('a/b.py').match('*.py')
505 True
506 >>> PurePath('/a/b/c.py').match('b/*.py')
507 True
508 >>> PurePath('/a/b/c.py').match('a/*.py')
509 False
510
511 If *pattern* is absolute, the path must be absolute, and the whole path
512 must match::
513
514 >>> PurePath('/a.py').match('/*.py')
515 True
516 >>> PurePath('a/b.py').match('/*.py')
517 False
518
519 As with other methods, case-sensitivity is observed::
520
521 >>> PureWindowsPath('b.py').match('*.PY')
522 True
523
524
525.. method:: PurePath.relative_to(*other)
526
527 Compute a version of this path relative to the path represented by
528 *other*. If it's impossible, ValueError is raised::
529
530 >>> p = PurePosixPath('/etc/passwd')
531 >>> p.relative_to('/')
532 PurePosixPath('etc/passwd')
533 >>> p.relative_to('/etc')
534 PurePosixPath('passwd')
535 >>> p.relative_to('/usr')
536 Traceback (most recent call last):
537 File "<stdin>", line 1, in <module>
538 File "pathlib.py", line 694, in relative_to
539 .format(str(self), str(formatted)))
540 ValueError: '/etc/passwd' does not start with '/usr'
541
542
Larry Hastings3732ed22014-03-15 21:13:56 -0700543.. method:: PurePath.with_name(name)
544
545 Return a new path with the :attr:`name` changed. If the original path
546 doesn't have a name, ValueError is raised::
547
548 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
549 >>> p.with_name('setup.py')
550 PureWindowsPath('c:/Downloads/setup.py')
551 >>> p = PureWindowsPath('c:/')
552 >>> p.with_name('setup.py')
553 Traceback (most recent call last):
554 File "<stdin>", line 1, in <module>
555 File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
556 raise ValueError("%r has an empty name" % (self,))
557 ValueError: PureWindowsPath('c:/') has an empty name
558
559
560.. method:: PurePath.with_suffix(suffix)
561
562 Return a new path with the :attr:`suffix` changed. If the original path
563 doesn't have a suffix, the new *suffix* is appended instead::
564
565 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
566 >>> p.with_suffix('.bz2')
567 PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
568 >>> p = PureWindowsPath('README')
569 >>> p.with_suffix('.txt')
570 PureWindowsPath('README.txt')
571
572
Antoine Pitrou31119e42013-11-22 17:38:12 +0100573.. _concrete-paths:
574
575
576Concrete paths
577--------------
578
579Concrete paths are subclasses of the pure path classes. In addition to
580operations provided by the latter, they also provide methods to do system
581calls on path objects. There are three ways to instantiate concrete paths:
582
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800583.. class:: Path(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100584
585 A subclass of :class:`PurePath`, this class represents concrete paths of
586 the system's path flavour (instantiating it creates either a
587 :class:`PosixPath` or a :class:`WindowsPath`)::
588
589 >>> Path('setup.py')
590 PosixPath('setup.py')
591
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800592 *pathsegments* is specified similarly to :class:`PurePath`.
593
594.. class:: PosixPath(*pathsegments)
595
596 A subclass of :class:`Path` and :class:`PurePosixPath`, this class
597 represents concrete non-Windows filesystem paths::
598
599 >>> PosixPath('/etc')
600 PosixPath('/etc')
601
602 *pathsegments* is specified similarly to :class:`PurePath`.
603
604.. class:: WindowsPath(*pathsegments)
605
606 A subclass of :class:`Path` and :class:`PureWindowsPath`, this class
607 represents concrete Windows filesystem paths::
608
609 >>> WindowsPath('c:/Program Files/')
610 WindowsPath('c:/Program Files')
611
612 *pathsegments* is specified similarly to :class:`PurePath`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100613
614You can only instantiate the class flavour that corresponds to your system
615(allowing system calls on non-compatible path flavours could lead to
616bugs or failures in your application)::
617
618 >>> import os
619 >>> os.name
620 'posix'
621 >>> Path('setup.py')
622 PosixPath('setup.py')
623 >>> PosixPath('setup.py')
624 PosixPath('setup.py')
625 >>> WindowsPath('setup.py')
626 Traceback (most recent call last):
627 File "<stdin>", line 1, in <module>
628 File "pathlib.py", line 798, in __new__
629 % (cls.__name__,))
630 NotImplementedError: cannot instantiate 'WindowsPath' on your system
631
632
633Methods
634^^^^^^^
635
636Concrete paths provide the following methods in addition to pure paths
637methods. Many of these methods can raise an :exc:`OSError` if a system
638call fails (for example because the path doesn't exist):
639
640.. classmethod:: Path.cwd()
641
642 Return a new path object representing the current directory (as returned
643 by :func:`os.getcwd`)::
644
645 >>> Path.cwd()
646 PosixPath('/home/antoine/pathlib')
647
648
649.. method:: Path.stat()
650
651 Return information about this path (similarly to :func:`os.stat`).
652 The result is looked up at each call to this method.
653
654 >>> p = Path('setup.py')
655 >>> p.stat().st_size
656 956
657 >>> p.stat().st_mtime
658 1327883547.852554
659
660
661.. method:: Path.chmod(mode)
662
663 Change the file mode and permissions, like :func:`os.chmod`::
664
665 >>> p = Path('setup.py')
666 >>> p.stat().st_mode
667 33277
668 >>> p.chmod(0o444)
669 >>> p.stat().st_mode
670 33060
671
672
673.. method:: Path.exists()
674
675 Whether the path points to an existing file or directory::
676
677 >>> Path('.').exists()
678 True
679 >>> Path('setup.py').exists()
680 True
681 >>> Path('/etc').exists()
682 True
683 >>> Path('nonexistentfile').exists()
684 False
685
686 .. note::
687 If the path points to a symlink, :meth:`exists` returns whether the
688 symlink *points to* an existing file or directory.
689
690
691.. method:: Path.glob(pattern)
692
693 Glob the given *pattern* in the directory represented by this path,
694 yielding all matching files (of any kind)::
695
696 >>> sorted(Path('.').glob('*.py'))
697 [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
698 >>> sorted(Path('.').glob('*/*.py'))
699 [PosixPath('docs/conf.py')]
700
701 The "``**``" pattern means "this directory and all subdirectories,
702 recursively". In other words, it enables recursive globbing::
703
704 >>> sorted(Path('.').glob('**/*.py'))
705 [PosixPath('build/lib/pathlib.py'),
706 PosixPath('docs/conf.py'),
707 PosixPath('pathlib.py'),
708 PosixPath('setup.py'),
709 PosixPath('test_pathlib.py')]
710
711 .. note::
712 Using the "``**``" pattern in large directory trees may consume
713 an inordinate amount of time.
714
715
716.. method:: Path.group()
717
Ned Deilyc0341562013-11-27 14:42:55 -0800718 Return the name of the group owning the file. :exc:`KeyError` is raised
Antoine Pitrou31119e42013-11-22 17:38:12 +0100719 if the file's gid isn't found in the system database.
720
721
722.. method:: Path.is_dir()
723
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200724 Return ``True`` if the path points to a directory (or a symbolic link
725 pointing to a directory), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100726
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200727 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100728 other errors (such as permission errors) are propagated.
729
730
731.. method:: Path.is_file()
732
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200733 Return ``True`` if the path points to a regular file (or a symbolic link
734 pointing to a regular file), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100735
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200736 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100737 other errors (such as permission errors) are propagated.
738
739
740.. method:: Path.is_symlink()
741
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200742 Return ``True`` if the path points to a symbolic link, ``False`` otherwise.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100743
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200744 ``False`` is also returned if the path doesn't exist; other errors (such
Antoine Pitrou31119e42013-11-22 17:38:12 +0100745 as permission errors) are propagated.
746
747
748.. method:: Path.is_socket()
749
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200750 Return ``True`` if the path points to a Unix socket (or a symbolic link
751 pointing to a Unix socket), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100752
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200753 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100754 other errors (such as permission errors) are propagated.
755
756
757.. method:: Path.is_fifo()
758
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200759 Return ``True`` if the path points to a FIFO (or a symbolic link
760 pointing to a FIFO), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100761
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200762 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100763 other errors (such as permission errors) are propagated.
764
765
766.. method:: Path.is_block_device()
767
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200768 Return ``True`` if the path points to a block device (or a symbolic link
769 pointing to a block device), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100770
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200771 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100772 other errors (such as permission errors) are propagated.
773
774
775.. method:: Path.is_char_device()
776
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200777 Return ``True`` if the path points to a character device (or a symbolic link
778 pointing to a character device), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100779
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200780 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100781 other errors (such as permission errors) are propagated.
782
783
784.. method:: Path.iterdir()
785
786 When the path points to a directory, yield path objects of the directory
787 contents::
788
789 >>> p = Path('docs')
790 >>> for child in p.iterdir(): child
791 ...
792 PosixPath('docs/conf.py')
793 PosixPath('docs/_templates')
794 PosixPath('docs/make.bat')
795 PosixPath('docs/index.rst')
796 PosixPath('docs/_build')
797 PosixPath('docs/_static')
798 PosixPath('docs/Makefile')
799
800.. method:: Path.lchmod(mode)
801
802 Like :meth:`Path.chmod` but, if the path points to a symbolic link, the
803 symbolic link's mode is changed rather than its target's.
804
805
806.. method:: Path.lstat()
807
808 Like :meth:`Path.stat` but, if the path points to a symbolic link, return
809 the symbolic link's information rather than its target's.
810
811
812.. method:: Path.mkdir(mode=0o777, parents=False)
813
814 Create a new directory at this given path. If *mode* is given, it is
815 combined with the process' ``umask`` value to determine the file mode
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100816 and access flags. If the path already exists, :exc:`FileExistsError`
817 is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100818
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200819 If *parents* is true, any missing parents of this path are created
Antoine Pitrou0048c982013-12-16 20:22:37 +0100820 as needed; they are created with the default permissions without taking
821 *mode* into account (mimicking the POSIX ``mkdir -p`` command).
822
823 If *parents* is false (the default), a missing parent raises
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100824 :exc:`FileNotFoundError`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100825
826
827.. method:: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
828
829 Open the file pointed to by the path, like the built-in :func:`open`
830 function does::
831
832 >>> p = Path('setup.py')
833 >>> with p.open() as f:
834 ... f.readline()
835 ...
836 '#!/usr/bin/env python3\n'
837
838
839.. method:: Path.owner()
840
Ned Deilyc0341562013-11-27 14:42:55 -0800841 Return the name of the user owning the file. :exc:`KeyError` is raised
Antoine Pitrou31119e42013-11-22 17:38:12 +0100842 if the file's uid isn't found in the system database.
843
844
845.. method:: Path.rename(target)
846
847 Rename this file or directory to the given *target*. *target* can be
848 either a string or another path object::
849
850 >>> p = Path('foo')
851 >>> p.open('w').write('some text')
852 9
853 >>> target = Path('bar')
854 >>> p.rename(target)
855 >>> target.open().read()
856 'some text'
857
858
859.. method:: Path.replace(target)
860
861 Rename this file or directory to the given *target*. If *target* points
862 to an existing file or directory, it will be unconditionally replaced.
863
864
865.. method:: Path.resolve()
866
867 Make the path absolute, resolving any symlinks. A new path object is
868 returned::
869
870 >>> p = Path()
871 >>> p
872 PosixPath('.')
873 >>> p.resolve()
874 PosixPath('/home/antoine/pathlib')
875
876 `".."` components are also eliminated (this is the only method to do so)::
877
878 >>> p = Path('docs/../setup.py')
879 >>> p.resolve()
880 PosixPath('/home/antoine/pathlib/setup.py')
881
882 If the path doesn't exist, :exc:`FileNotFoundError` is raised. If an
883 infinite loop is encountered along the resolution path,
884 :exc:`RuntimeError` is raised.
885
886
887.. method:: Path.rglob(pattern)
888
889 This is like calling :meth:`glob` with "``**``" added in front of the
890 given *pattern*:
891
892 >>> sorted(Path().rglob("*.py"))
893 [PosixPath('build/lib/pathlib.py'),
894 PosixPath('docs/conf.py'),
895 PosixPath('pathlib.py'),
896 PosixPath('setup.py'),
897 PosixPath('test_pathlib.py')]
898
899
900.. method:: Path.rmdir()
901
902 Remove this directory. The directory must be empty.
903
904
905.. method:: Path.symlink_to(target, target_is_directory=False)
906
907 Make this path a symbolic link to *target*. Under Windows,
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200908 *target_is_directory* must be true (default ``False``) if the link's target
Antoine Pitrou31119e42013-11-22 17:38:12 +0100909 is a directory. Under POSIX, *target_is_directory*'s value is ignored.
910
911 >>> p = Path('mylink')
912 >>> p.symlink_to('setup.py')
913 >>> p.resolve()
914 PosixPath('/home/antoine/pathlib/setup.py')
915 >>> p.stat().st_size
916 956
917 >>> p.lstat().st_size
918 8
919
920 .. note::
921 The order of arguments (link, target) is the reverse
922 of :func:`os.symlink`'s.
923
924
925.. method:: Path.touch(mode=0o777, exist_ok=True)
926
927 Create a file at this given path. If *mode* is given, it is combined
928 with the process' ``umask`` value to determine the file mode and access
929 flags. If the file already exists, the function succeeds if *exist_ok*
930 is true (and its modification time is updated to the current time),
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100931 otherwise :exc:`FileExistsError` is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100932
933
934.. method:: Path.unlink()
935
936 Remove this file or symbolic link. If the path points to a directory,
937 use :func:`Path.rmdir` instead.