blob: b6507eb4d6fa2c1e9e581f8059ee3ebb3a68ec9f [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
Hai Shi82642a02019-08-13 14:54:02 -0500276 from pathlib import PurePath, PurePosixPath, PureWindowsPath
Marco Buttu7b2491a2017-04-13 16:17:59 +0200277
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
Joshua Cannon45205842020-11-20 09:40:39 -0600339 .. versionchanged:: 3.10
Yaroslav Pankovych79d2e622020-11-23 22:06:22 +0200340 The parents sequence now supports :term:`slices <slice>` and negative index values.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100341
342.. data:: PurePath.parent
343
344 The logical parent of the path::
345
346 >>> p = PurePosixPath('/a/b/c/d')
347 >>> p.parent
348 PurePosixPath('/a/b/c')
349
350 You cannot go past an anchor, or empty path::
351
352 >>> p = PurePosixPath('/')
353 >>> p.parent
354 PurePosixPath('/')
355 >>> p = PurePosixPath('.')
356 >>> p.parent
357 PurePosixPath('.')
358
359 .. note::
360 This is a purely lexical operation, hence the following behaviour::
361
362 >>> p = PurePosixPath('foo/..')
363 >>> p.parent
364 PurePosixPath('foo')
365
366 If you want to walk an arbitrary filesystem path upwards, it is
367 recommended to first call :meth:`Path.resolve` so as to resolve
368 symlinks and eliminate `".."` components.
369
370
371.. data:: PurePath.name
372
373 A string representing the final path component, excluding the drive and
374 root, if any::
375
376 >>> PurePosixPath('my/library/setup.py').name
377 'setup.py'
378
379 UNC drive names are not considered::
380
381 >>> PureWindowsPath('//some/share/setup.py').name
382 'setup.py'
383 >>> PureWindowsPath('//some/share').name
384 ''
385
386
387.. data:: PurePath.suffix
388
389 The file extension of the final component, if any::
390
391 >>> PurePosixPath('my/library/setup.py').suffix
392 '.py'
393 >>> PurePosixPath('my/library.tar.gz').suffix
394 '.gz'
395 >>> PurePosixPath('my/library').suffix
396 ''
397
398
399.. data:: PurePath.suffixes
400
401 A list of the path's file extensions::
402
403 >>> PurePosixPath('my/library.tar.gar').suffixes
404 ['.tar', '.gar']
405 >>> PurePosixPath('my/library.tar.gz').suffixes
406 ['.tar', '.gz']
407 >>> PurePosixPath('my/library').suffixes
408 []
409
410
411.. data:: PurePath.stem
412
413 The final path component, without its suffix::
414
415 >>> PurePosixPath('my/library.tar.gz').stem
416 'library.tar'
417 >>> PurePosixPath('my/library.tar').stem
418 'library'
419 >>> PurePosixPath('my/library').stem
420 'library'
421
422
423.. method:: PurePath.as_posix()
424
425 Return a string representation of the path with forward slashes (``/``)::
426
427 >>> p = PureWindowsPath('c:\\windows')
428 >>> str(p)
429 'c:\\windows'
430 >>> p.as_posix()
431 'c:/windows'
432
433
434.. method:: PurePath.as_uri()
435
436 Represent the path as a ``file`` URI. :exc:`ValueError` is raised if
437 the path isn't absolute.
438
439 >>> p = PurePosixPath('/etc/passwd')
440 >>> p.as_uri()
441 'file:///etc/passwd'
442 >>> p = PureWindowsPath('c:/Windows')
443 >>> p.as_uri()
444 'file:///c:/Windows'
445
446
447.. method:: PurePath.is_absolute()
448
449 Return whether the path is absolute or not. A path is considered absolute
450 if it has both a root and (if the flavour allows) a drive::
451
452 >>> PurePosixPath('/a/b').is_absolute()
453 True
454 >>> PurePosixPath('a/b').is_absolute()
455 False
456
457 >>> PureWindowsPath('c:/a/b').is_absolute()
458 True
459 >>> PureWindowsPath('/a/b').is_absolute()
460 False
461 >>> PureWindowsPath('c:').is_absolute()
462 False
463 >>> PureWindowsPath('//some/share').is_absolute()
464 True
465
466
Hai Shi82642a02019-08-13 14:54:02 -0500467.. method:: PurePath.is_relative_to(*other)
468
469 Return whether or not this path is relative to the *other* path.
470
471 >>> p = PurePath('/etc/passwd')
472 >>> p.is_relative_to('/etc')
473 True
474 >>> p.is_relative_to('/usr')
475 False
476
477 .. versionadded:: 3.9
478
479
Antoine Pitrou31119e42013-11-22 17:38:12 +0100480.. method:: PurePath.is_reserved()
481
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200482 With :class:`PureWindowsPath`, return ``True`` if the path is considered
483 reserved under Windows, ``False`` otherwise. With :class:`PurePosixPath`,
484 ``False`` is always returned.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100485
486 >>> PureWindowsPath('nul').is_reserved()
487 True
488 >>> PurePosixPath('nul').is_reserved()
489 False
490
491 File system calls on reserved paths can fail mysteriously or have
492 unintended effects.
493
494
495.. method:: PurePath.joinpath(*other)
496
Andrew Kuchling7a4e2d12013-11-22 15:45:02 -0500497 Calling this method is equivalent to combining the path with each of
Antoine Pitrou31119e42013-11-22 17:38:12 +0100498 the *other* arguments in turn::
499
500 >>> PurePosixPath('/etc').joinpath('passwd')
501 PurePosixPath('/etc/passwd')
502 >>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
503 PurePosixPath('/etc/passwd')
504 >>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
505 PurePosixPath('/etc/init.d/apache2')
506 >>> PureWindowsPath('c:').joinpath('/Program Files')
507 PureWindowsPath('c:/Program Files')
508
509
510.. method:: PurePath.match(pattern)
511
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200512 Match this path against the provided glob-style pattern. Return ``True``
513 if matching is successful, ``False`` otherwise.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100514
515 If *pattern* is relative, the path can be either relative or absolute,
516 and matching is done from the right::
517
518 >>> PurePath('a/b.py').match('*.py')
519 True
520 >>> PurePath('/a/b/c.py').match('b/*.py')
521 True
522 >>> PurePath('/a/b/c.py').match('a/*.py')
523 False
524
525 If *pattern* is absolute, the path must be absolute, and the whole path
526 must match::
527
528 >>> PurePath('/a.py').match('/*.py')
529 True
530 >>> PurePath('a/b.py').match('/*.py')
531 False
532
Tim Loc12375a2020-04-19 05:43:11 -0400533 As with other methods, case-sensitivity follows platform defaults::
Antoine Pitrou31119e42013-11-22 17:38:12 +0100534
Tim Loc12375a2020-04-19 05:43:11 -0400535 >>> PurePosixPath('b.py').match('*.PY')
536 False
Antoine Pitrou31119e42013-11-22 17:38:12 +0100537 >>> PureWindowsPath('b.py').match('*.PY')
538 True
539
540
541.. method:: PurePath.relative_to(*other)
542
543 Compute a version of this path relative to the path represented by
544 *other*. If it's impossible, ValueError is raised::
545
546 >>> p = PurePosixPath('/etc/passwd')
547 >>> p.relative_to('/')
548 PurePosixPath('etc/passwd')
549 >>> p.relative_to('/etc')
550 PurePosixPath('passwd')
551 >>> p.relative_to('/usr')
552 Traceback (most recent call last):
553 File "<stdin>", line 1, in <module>
554 File "pathlib.py", line 694, in relative_to
555 .format(str(self), str(formatted)))
Rotuna44832532020-05-25 21:42:28 +0200556 ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other absolute.
557
558 NOTE: This function is part of :class:`PurePath` and works with strings. It does not check or access the underlying file structure.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100559
560
Antoine Pitrouef851192014-02-25 20:33:02 +0100561.. method:: PurePath.with_name(name)
562
563 Return a new path with the :attr:`name` changed. If the original path
564 doesn't have a name, ValueError is raised::
565
566 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
567 >>> p.with_name('setup.py')
568 PureWindowsPath('c:/Downloads/setup.py')
569 >>> p = PureWindowsPath('c:/')
570 >>> p.with_name('setup.py')
571 Traceback (most recent call last):
572 File "<stdin>", line 1, in <module>
573 File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
574 raise ValueError("%r has an empty name" % (self,))
575 ValueError: PureWindowsPath('c:/') has an empty name
576
577
Tim Hoffmann8aea4b32020-04-19 17:29:49 +0200578.. method:: PurePath.with_stem(stem)
579
580 Return a new path with the :attr:`stem` changed. If the original path
581 doesn't have a name, ValueError is raised::
582
583 >>> p = PureWindowsPath('c:/Downloads/draft.txt')
584 >>> p.with_stem('final')
585 PureWindowsPath('c:/Downloads/final.txt')
586 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
587 >>> p.with_stem('lib')
588 PureWindowsPath('c:/Downloads/lib.gz')
589 >>> p = PureWindowsPath('c:/')
590 >>> p.with_stem('')
591 Traceback (most recent call last):
592 File "<stdin>", line 1, in <module>
593 File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem
594 return self.with_name(stem + self.suffix)
595 File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name
596 raise ValueError("%r has an empty name" % (self,))
597 ValueError: PureWindowsPath('c:/') has an empty name
598
599 .. versionadded:: 3.9
600
601
Antoine Pitrouef851192014-02-25 20:33:02 +0100602.. method:: PurePath.with_suffix(suffix)
603
604 Return a new path with the :attr:`suffix` changed. If the original path
Stefan Otte46dc4e32018-08-03 22:49:42 +0200605 doesn't have a suffix, the new *suffix* is appended instead. If the
606 *suffix* is an empty string, the original suffix is removed::
Antoine Pitrouef851192014-02-25 20:33:02 +0100607
608 >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
609 >>> p.with_suffix('.bz2')
610 PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
611 >>> p = PureWindowsPath('README')
612 >>> p.with_suffix('.txt')
613 PureWindowsPath('README.txt')
Stefan Otte46dc4e32018-08-03 22:49:42 +0200614 >>> p = PureWindowsPath('README.txt')
615 >>> p.with_suffix('')
616 PureWindowsPath('README')
Antoine Pitrouef851192014-02-25 20:33:02 +0100617
618
Antoine Pitrou31119e42013-11-22 17:38:12 +0100619.. _concrete-paths:
620
621
622Concrete paths
623--------------
624
625Concrete paths are subclasses of the pure path classes. In addition to
626operations provided by the latter, they also provide methods to do system
627calls on path objects. There are three ways to instantiate concrete paths:
628
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800629.. class:: Path(*pathsegments)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100630
631 A subclass of :class:`PurePath`, this class represents concrete paths of
632 the system's path flavour (instantiating it creates either a
633 :class:`PosixPath` or a :class:`WindowsPath`)::
634
635 >>> Path('setup.py')
636 PosixPath('setup.py')
637
Eli Benderskyb6e66eb2013-11-28 06:53:05 -0800638 *pathsegments* is specified similarly to :class:`PurePath`.
639
640.. class:: PosixPath(*pathsegments)
641
642 A subclass of :class:`Path` and :class:`PurePosixPath`, this class
643 represents concrete non-Windows filesystem paths::
644
645 >>> PosixPath('/etc')
646 PosixPath('/etc')
647
648 *pathsegments* is specified similarly to :class:`PurePath`.
649
650.. class:: WindowsPath(*pathsegments)
651
652 A subclass of :class:`Path` and :class:`PureWindowsPath`, this class
653 represents concrete Windows filesystem paths::
654
655 >>> WindowsPath('c:/Program Files/')
656 WindowsPath('c:/Program Files')
657
658 *pathsegments* is specified similarly to :class:`PurePath`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100659
660You can only instantiate the class flavour that corresponds to your system
661(allowing system calls on non-compatible path flavours could lead to
662bugs or failures in your application)::
663
664 >>> import os
665 >>> os.name
666 'posix'
667 >>> Path('setup.py')
668 PosixPath('setup.py')
669 >>> PosixPath('setup.py')
670 PosixPath('setup.py')
671 >>> WindowsPath('setup.py')
672 Traceback (most recent call last):
673 File "<stdin>", line 1, in <module>
674 File "pathlib.py", line 798, in __new__
675 % (cls.__name__,))
676 NotImplementedError: cannot instantiate 'WindowsPath' on your system
677
678
679Methods
680^^^^^^^
681
682Concrete paths provide the following methods in addition to pure paths
683methods. Many of these methods can raise an :exc:`OSError` if a system
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300684call fails (for example because the path doesn't exist).
685
686.. versionchanged:: 3.8
687
688 :meth:`~Path.exists()`, :meth:`~Path.is_dir()`, :meth:`~Path.is_file()`,
689 :meth:`~Path.is_mount()`, :meth:`~Path.is_symlink()`,
690 :meth:`~Path.is_block_device()`, :meth:`~Path.is_char_device()`,
691 :meth:`~Path.is_fifo()`, :meth:`~Path.is_socket()` now return ``False``
692 instead of raising an exception for paths that contain characters
693 unrepresentable at the OS level.
694
Antoine Pitrou31119e42013-11-22 17:38:12 +0100695
696.. classmethod:: Path.cwd()
697
698 Return a new path object representing the current directory (as returned
699 by :func:`os.getcwd`)::
700
701 >>> Path.cwd()
702 PosixPath('/home/antoine/pathlib')
703
704
Antoine Pitrou17cba7d2015-01-12 21:03:41 +0100705.. classmethod:: Path.home()
706
707 Return a new path object representing the user's home directory (as
Barney Gale3f3d82b2021-04-07 23:50:13 +0100708 returned by :func:`os.path.expanduser` with ``~`` construct). If the home
709 directory can't be resolved, :exc:`RuntimeError` is raised.
710
711 ::
Antoine Pitrou17cba7d2015-01-12 21:03:41 +0100712
713 >>> Path.home()
714 PosixPath('/home/antoine')
715
716 .. versionadded:: 3.5
717
718
Barney Galeabf96492021-04-07 16:53:39 +0100719.. method:: Path.stat(*, follow_symlinks=True)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100720
Brett Cannon67152d02020-03-04 14:51:50 -0800721 Return a :class:`os.stat_result` object containing information about this path, like :func:`os.stat`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100722 The result is looked up at each call to this method.
723
Barney Galeabf96492021-04-07 16:53:39 +0100724 This method normally follows symlinks; to stat a symlink add the argument
725 ``follow_symlinks=False``, or use :meth:`~Path.lstat`.
726
Marco Buttu7b2491a2017-04-13 16:17:59 +0200727 ::
728
Antoine Pitrou31119e42013-11-22 17:38:12 +0100729 >>> p = Path('setup.py')
730 >>> p.stat().st_size
731 956
732 >>> p.stat().st_mtime
733 1327883547.852554
734
Barney Galeabf96492021-04-07 16:53:39 +0100735 .. versionchanged:: 3.10
736 The *follow_symlinks* parameter was added.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100737
Barney Galeabf96492021-04-07 16:53:39 +0100738.. method:: Path.chmod(mode, *, follow_symlinks=True)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100739
Barney Galeabf96492021-04-07 16:53:39 +0100740 Change the file mode and permissions, like :func:`os.chmod`.
741
742 This method normally follows symlinks. Some Unix flavours support changing
743 permissions on the symlink itself; on these platforms you may add the
744 argument ``follow_symlinks=False``, or use :meth:`~Path.lchmod`.
745
746 ::
Antoine Pitrou31119e42013-11-22 17:38:12 +0100747
748 >>> p = Path('setup.py')
749 >>> p.stat().st_mode
750 33277
751 >>> p.chmod(0o444)
752 >>> p.stat().st_mode
753 33060
754
Barney Galeabf96492021-04-07 16:53:39 +0100755 .. versionchanged:: 3.10
756 The *follow_symlinks* parameter was added.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100757
758.. method:: Path.exists()
759
760 Whether the path points to an existing file or directory::
761
762 >>> Path('.').exists()
763 True
764 >>> Path('setup.py').exists()
765 True
766 >>> Path('/etc').exists()
767 True
768 >>> Path('nonexistentfile').exists()
769 False
770
771 .. note::
772 If the path points to a symlink, :meth:`exists` returns whether the
773 symlink *points to* an existing file or directory.
774
775
Antoine Pitrou8477ed62014-12-30 20:54:45 +0100776.. method:: Path.expanduser()
777
778 Return a new path with expanded ``~`` and ``~user`` constructs,
Barney Gale3f3d82b2021-04-07 23:50:13 +0100779 as returned by :meth:`os.path.expanduser`. If a home directory can't be
780 resolved, :exc:`RuntimeError` is raised.
781
782 ::
Antoine Pitrou8477ed62014-12-30 20:54:45 +0100783
784 >>> p = PosixPath('~/films/Monty Python')
785 >>> p.expanduser()
786 PosixPath('/home/eric/films/Monty Python')
787
788 .. versionadded:: 3.5
789
790
Antoine Pitrou31119e42013-11-22 17:38:12 +0100791.. method:: Path.glob(pattern)
792
Eivind Teig537b6ca2019-02-11 11:47:09 +0100793 Glob the given relative *pattern* in the directory represented by this path,
Antoine Pitrou31119e42013-11-22 17:38:12 +0100794 yielding all matching files (of any kind)::
795
796 >>> sorted(Path('.').glob('*.py'))
797 [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
798 >>> sorted(Path('.').glob('*/*.py'))
799 [PosixPath('docs/conf.py')]
800
Ned Batchelderb2b6cd02021-04-20 12:45:45 -0400801 Patterns are the same as for :mod:`fnmatch`, with the addition of "``**``"
802 which means "this directory and all subdirectories, recursively". In other
803 words, it enables recursive globbing::
Antoine Pitrou31119e42013-11-22 17:38:12 +0100804
805 >>> sorted(Path('.').glob('**/*.py'))
806 [PosixPath('build/lib/pathlib.py'),
807 PosixPath('docs/conf.py'),
808 PosixPath('pathlib.py'),
809 PosixPath('setup.py'),
810 PosixPath('test_pathlib.py')]
811
812 .. note::
813 Using the "``**``" pattern in large directory trees may consume
814 an inordinate amount of time.
815
Serhiy Storchakadb283b32020-03-08 14:31:47 +0200816 .. audit-event:: pathlib.Path.glob self,pattern pathlib.Path.glob
817
Antoine Pitrou31119e42013-11-22 17:38:12 +0100818
819.. method:: Path.group()
820
Ned Deilyc0341562013-11-27 14:42:55 -0800821 Return the name of the group owning the file. :exc:`KeyError` is raised
Antoine Pitrou31119e42013-11-22 17:38:12 +0100822 if the file's gid isn't found in the system database.
823
824
825.. method:: Path.is_dir()
826
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200827 Return ``True`` if the path points to a directory (or a symbolic link
828 pointing to a directory), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100829
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200830 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100831 other errors (such as permission errors) are propagated.
832
833
834.. method:: Path.is_file()
835
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200836 Return ``True`` if the path points to a regular file (or a symbolic link
837 pointing to a regular file), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100838
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200839 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100840 other errors (such as permission errors) are propagated.
841
842
Łukasz Langa47320a62017-08-01 16:47:50 -0700843.. method:: Path.is_mount()
844
845 Return ``True`` if the path is a :dfn:`mount point`: a point in a
846 file system where a different file system has been mounted. On POSIX, the
847 function checks whether *path*'s parent, :file:`path/..`, is on a different
848 device than *path*, or whether :file:`path/..` and *path* point to the same
849 i-node on the same device --- this should detect mount points for all Unix
850 and POSIX variants. Not implemented on Windows.
851
852 .. versionadded:: 3.7
853
854
Antoine Pitrou31119e42013-11-22 17:38:12 +0100855.. method:: Path.is_symlink()
856
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200857 Return ``True`` if the path points to a symbolic link, ``False`` otherwise.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100858
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200859 ``False`` is also returned if the path doesn't exist; other errors (such
Antoine Pitrou31119e42013-11-22 17:38:12 +0100860 as permission errors) are propagated.
861
862
863.. method:: Path.is_socket()
864
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200865 Return ``True`` if the path points to a Unix socket (or a symbolic link
866 pointing to a Unix socket), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100867
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200868 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100869 other errors (such as permission errors) are propagated.
870
871
872.. method:: Path.is_fifo()
873
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200874 Return ``True`` if the path points to a FIFO (or a symbolic link
875 pointing to a FIFO), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100876
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200877 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100878 other errors (such as permission errors) are propagated.
879
880
881.. method:: Path.is_block_device()
882
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200883 Return ``True`` if the path points to a block device (or a symbolic link
884 pointing to a block device), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100885
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200886 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100887 other errors (such as permission errors) are propagated.
888
889
890.. method:: Path.is_char_device()
891
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200892 Return ``True`` if the path points to a character device (or a symbolic link
893 pointing to a character device), ``False`` if it points to another kind of file.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100894
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200895 ``False`` is also returned if the path doesn't exist or is a broken symlink;
Antoine Pitrou31119e42013-11-22 17:38:12 +0100896 other errors (such as permission errors) are propagated.
897
898
899.. method:: Path.iterdir()
900
901 When the path points to a directory, yield path objects of the directory
902 contents::
903
904 >>> p = Path('docs')
905 >>> for child in p.iterdir(): child
906 ...
907 PosixPath('docs/conf.py')
908 PosixPath('docs/_templates')
909 PosixPath('docs/make.bat')
910 PosixPath('docs/index.rst')
911 PosixPath('docs/_build')
912 PosixPath('docs/_static')
913 PosixPath('docs/Makefile')
914
Serhiy Storchaka306cfb32020-09-04 21:19:30 +0300915 The children are yielded in arbitrary order, and the special entries
916 ``'.'`` and ``'..'`` are not included. If a file is removed from or added
917 to the directory after creating the iterator, whether an path object for
918 that file be included is unspecified.
919
Antoine Pitrou31119e42013-11-22 17:38:12 +0100920.. method:: Path.lchmod(mode)
921
922 Like :meth:`Path.chmod` but, if the path points to a symbolic link, the
923 symbolic link's mode is changed rather than its target's.
924
925
926.. method:: Path.lstat()
927
928 Like :meth:`Path.stat` but, if the path points to a symbolic link, return
929 the symbolic link's information rather than its target's.
930
931
Barry Warsaw7c549c42014-08-05 11:28:12 -0400932.. method:: Path.mkdir(mode=0o777, parents=False, exist_ok=False)
Antoine Pitrou31119e42013-11-22 17:38:12 +0100933
934 Create a new directory at this given path. If *mode* is given, it is
935 combined with the process' ``umask`` value to determine the file mode
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100936 and access flags. If the path already exists, :exc:`FileExistsError`
937 is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100938
Serhiy Storchaka03cc5652013-11-26 21:37:12 +0200939 If *parents* is true, any missing parents of this path are created
Antoine Pitrou0048c982013-12-16 20:22:37 +0100940 as needed; they are created with the default permissions without taking
941 *mode* into account (mimicking the POSIX ``mkdir -p`` command).
942
943 If *parents* is false (the default), a missing parent raises
Antoine Pitrouf6abb702013-12-16 21:00:53 +0100944 :exc:`FileNotFoundError`.
Antoine Pitrou31119e42013-11-22 17:38:12 +0100945
Ned Deily11194f72016-10-15 15:12:03 -0400946 If *exist_ok* is false (the default), :exc:`FileExistsError` is
Barry Warsaw7c549c42014-08-05 11:28:12 -0400947 raised if the target directory already exists.
948
949 If *exist_ok* is true, :exc:`FileExistsError` exceptions will be
950 ignored (same behavior as the POSIX ``mkdir -p`` command), but only if the
951 last path component is not an existing non-directory file.
952
953 .. versionchanged:: 3.5
954 The *exist_ok* parameter was added.
955
Antoine Pitrou31119e42013-11-22 17:38:12 +0100956
957.. method:: Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)
958
959 Open the file pointed to by the path, like the built-in :func:`open`
960 function does::
961
962 >>> p = Path('setup.py')
963 >>> with p.open() as f:
964 ... f.readline()
965 ...
966 '#!/usr/bin/env python3\n'
967
968
969.. method:: Path.owner()
970
Ned Deilyc0341562013-11-27 14:42:55 -0800971 Return the name of the user owning the file. :exc:`KeyError` is raised
Antoine Pitrou31119e42013-11-22 17:38:12 +0100972 if the file's uid isn't found in the system database.
973
974
Georg Brandlea683982014-10-01 19:12:33 +0200975.. method:: Path.read_bytes()
976
977 Return the binary contents of the pointed-to file as a bytes object::
978
979 >>> p = Path('my_binary_file')
980 >>> p.write_bytes(b'Binary file contents')
981 20
982 >>> p.read_bytes()
983 b'Binary file contents'
984
985 .. versionadded:: 3.5
986
987
988.. method:: Path.read_text(encoding=None, errors=None)
989
990 Return the decoded contents of the pointed-to file as a string::
991
992 >>> p = Path('my_text_file')
993 >>> p.write_text('Text file contents')
994 18
995 >>> p.read_text()
996 'Text file contents'
997
Xtreak5b2657f2018-08-07 01:25:03 +0530998 The file is opened and then closed. The optional parameters have the same
999 meaning as in :func:`open`.
Georg Brandlea683982014-10-01 19:12:33 +02001000
1001 .. versionadded:: 3.5
1002
1003
Girtsa01ba332019-10-23 14:18:40 -07001004.. method:: Path.readlink()
1005
1006 Return the path to which the symbolic link points (as returned by
1007 :func:`os.readlink`)::
1008
1009 >>> p = Path('mylink')
1010 >>> p.symlink_to('setup.py')
1011 >>> p.readlink()
1012 PosixPath('setup.py')
1013
1014 .. versionadded:: 3.9
1015
1016
Antoine Pitrou31119e42013-11-22 17:38:12 +01001017.. method:: Path.rename(target)
1018
hui shang088a09a2019-09-11 21:26:49 +08001019 Rename this file or directory to the given *target*, and return a new Path
1020 instance pointing to *target*. On Unix, if *target* exists and is a file,
1021 it will be replaced silently if the user has permission. *target* can be
1022 either a string or another path object::
Antoine Pitrou31119e42013-11-22 17:38:12 +01001023
1024 >>> p = Path('foo')
1025 >>> p.open('w').write('some text')
1026 9
1027 >>> target = Path('bar')
1028 >>> p.rename(target)
hui shang088a09a2019-09-11 21:26:49 +08001029 PosixPath('bar')
Antoine Pitrou31119e42013-11-22 17:38:12 +01001030 >>> target.open().read()
1031 'some text'
1032
Ram Rachumf97e42e2020-10-03 12:52:13 +03001033 The target path may be absolute or relative. Relative paths are interpreted
1034 relative to the current working directory, *not* the directory of the Path
1035 object.
1036
hui shang088a09a2019-09-11 21:26:49 +08001037 .. versionchanged:: 3.8
1038 Added return value, return the new Path instance.
1039
Antoine Pitrou31119e42013-11-22 17:38:12 +01001040
1041.. method:: Path.replace(target)
1042
hui shang088a09a2019-09-11 21:26:49 +08001043 Rename this file or directory to the given *target*, and return a new Path
1044 instance pointing to *target*. If *target* points to an existing file or
1045 directory, it will be unconditionally replaced.
1046
Ram Rachumf97e42e2020-10-03 12:52:13 +03001047 The target path may be absolute or relative. Relative paths are interpreted
1048 relative to the current working directory, *not* the directory of the Path
1049 object.
1050
hui shang088a09a2019-09-11 21:26:49 +08001051 .. versionchanged:: 3.8
1052 Added return value, return the new Path instance.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001053
1054
Steve Dower98eb3602016-11-09 12:58:17 -08001055.. method:: Path.resolve(strict=False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001056
1057 Make the path absolute, resolving any symlinks. A new path object is
1058 returned::
1059
1060 >>> p = Path()
1061 >>> p
1062 PosixPath('.')
1063 >>> p.resolve()
1064 PosixPath('/home/antoine/pathlib')
1065
Berker Peksag5e3677d2016-10-01 01:06:52 +03001066 "``..``" components are also eliminated (this is the only method to do so)::
Antoine Pitrou31119e42013-11-22 17:38:12 +01001067
1068 >>> p = Path('docs/../setup.py')
1069 >>> p.resolve()
1070 PosixPath('/home/antoine/pathlib/setup.py')
1071
Steve Dower98eb3602016-11-09 12:58:17 -08001072 If the path doesn't exist and *strict* is ``True``, :exc:`FileNotFoundError`
1073 is raised. If *strict* is ``False``, the path is resolved as far as possible
1074 and any remainder is appended without checking whether it exists. If an
1075 infinite loop is encountered along the resolution path, :exc:`RuntimeError`
1076 is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001077
Steve Dower98eb3602016-11-09 12:58:17 -08001078 .. versionadded:: 3.6
Julien Palard1d4b1602019-05-08 17:01:11 +02001079 The *strict* argument (pre-3.6 behavior is strict).
Antoine Pitrou31119e42013-11-22 17:38:12 +01001080
1081.. method:: Path.rglob(pattern)
1082
Eivind Teig537b6ca2019-02-11 11:47:09 +01001083 This is like calling :func:`Path.glob` with "``**/``" added in front of the
1084 given relative *pattern*::
Antoine Pitrou31119e42013-11-22 17:38:12 +01001085
1086 >>> sorted(Path().rglob("*.py"))
1087 [PosixPath('build/lib/pathlib.py'),
1088 PosixPath('docs/conf.py'),
1089 PosixPath('pathlib.py'),
1090 PosixPath('setup.py'),
1091 PosixPath('test_pathlib.py')]
1092
Serhiy Storchakadb283b32020-03-08 14:31:47 +02001093 .. audit-event:: pathlib.Path.rglob self,pattern pathlib.Path.rglob
1094
Antoine Pitrou31119e42013-11-22 17:38:12 +01001095
1096.. method:: Path.rmdir()
1097
1098 Remove this directory. The directory must be empty.
1099
1100
Antoine Pitrou43e3d942014-05-13 10:50:15 +02001101.. method:: Path.samefile(other_path)
1102
1103 Return whether this path points to the same file as *other_path*, which
1104 can be either a Path object, or a string. The semantics are similar
1105 to :func:`os.path.samefile` and :func:`os.path.samestat`.
1106
1107 An :exc:`OSError` can be raised if either file cannot be accessed for some
1108 reason.
1109
Marco Buttu7b2491a2017-04-13 16:17:59 +02001110 ::
1111
Antoine Pitrou43e3d942014-05-13 10:50:15 +02001112 >>> p = Path('spam')
1113 >>> q = Path('eggs')
1114 >>> p.samefile(q)
1115 False
1116 >>> p.samefile('spam')
1117 True
1118
1119 .. versionadded:: 3.5
1120
1121
Antoine Pitrou31119e42013-11-22 17:38:12 +01001122.. method:: Path.symlink_to(target, target_is_directory=False)
1123
1124 Make this path a symbolic link to *target*. Under Windows,
Serhiy Storchaka03cc5652013-11-26 21:37:12 +02001125 *target_is_directory* must be true (default ``False``) if the link's target
Antoine Pitrou31119e42013-11-22 17:38:12 +01001126 is a directory. Under POSIX, *target_is_directory*'s value is ignored.
1127
Marco Buttu7b2491a2017-04-13 16:17:59 +02001128 ::
1129
Antoine Pitrou31119e42013-11-22 17:38:12 +01001130 >>> p = Path('mylink')
1131 >>> p.symlink_to('setup.py')
1132 >>> p.resolve()
1133 PosixPath('/home/antoine/pathlib/setup.py')
1134 >>> p.stat().st_size
1135 956
1136 >>> p.lstat().st_size
1137 8
1138
1139 .. note::
1140 The order of arguments (link, target) is the reverse
1141 of :func:`os.symlink`'s.
1142
Barney Galef24e2e52021-04-23 21:48:52 +01001143.. method:: Path.hardlink_to(target)
1144
1145 Make this path a hard link to the same file as *target*.
1146
1147 .. note::
1148 The order of arguments (link, target) is the reverse
1149 of :func:`os.link`'s.
1150
1151 .. versionadded:: 3.10
Antoine Pitrou31119e42013-11-22 17:38:12 +01001152
Barney Gale8aac1be2021-04-07 16:56:32 +01001153.. method:: Path.link_to(target)
1154
1155 Make *target* a hard link to this path.
1156
1157 .. warning::
1158
1159 This function does not make this path a hard link to *target*, despite
1160 the implication of the function and argument names. The argument order
Barney Galef24e2e52021-04-23 21:48:52 +01001161 (target, link) is the reverse of :func:`Path.symlink_to` and
1162 :func:`Path.hardlink_to`, but matches that of :func:`os.link`.
Barney Gale8aac1be2021-04-07 16:56:32 +01001163
1164 .. versionadded:: 3.8
1165
Barney Galef24e2e52021-04-23 21:48:52 +01001166 .. deprecated:: 3.10
1167
1168 This method is deprecated in favor of :meth:`Path.hardlink_to`, as the
1169 argument order of :meth:`Path.link_to` does not match that of
1170 :meth:`Path.symlink_to`.
1171
Barney Gale8aac1be2021-04-07 16:56:32 +01001172
Zachary Ware7a26da52016-08-09 17:10:39 -05001173.. method:: Path.touch(mode=0o666, exist_ok=True)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001174
1175 Create a file at this given path. If *mode* is given, it is combined
1176 with the process' ``umask`` value to determine the file mode and access
1177 flags. If the file already exists, the function succeeds if *exist_ok*
1178 is true (and its modification time is updated to the current time),
Antoine Pitrouf6abb702013-12-16 21:00:53 +01001179 otherwise :exc:`FileExistsError` is raised.
Antoine Pitrou31119e42013-11-22 17:38:12 +01001180
1181
‮zlohhcuB treboRd9e006b2019-05-16 00:02:11 +02001182.. method:: Path.unlink(missing_ok=False)
Antoine Pitrou31119e42013-11-22 17:38:12 +01001183
1184 Remove this file or symbolic link. If the path points to a directory,
1185 use :func:`Path.rmdir` instead.
Georg Brandlea683982014-10-01 19:12:33 +02001186
‮zlohhcuB treboRd9e006b2019-05-16 00:02:11 +02001187 If *missing_ok* is false (the default), :exc:`FileNotFoundError` is
1188 raised if the path does not exist.
1189
1190 If *missing_ok* is true, :exc:`FileNotFoundError` exceptions will be
1191 ignored (same behavior as the POSIX ``rm -f`` command).
1192
1193 .. versionchanged:: 3.8
1194 The *missing_ok* parameter was added.
1195
Georg Brandlea683982014-10-01 19:12:33 +02001196
1197.. method:: Path.write_bytes(data)
1198
1199 Open the file pointed to in bytes mode, write *data* to it, and close the
1200 file::
1201
1202 >>> p = Path('my_binary_file')
1203 >>> p.write_bytes(b'Binary file contents')
1204 20
1205 >>> p.read_bytes()
1206 b'Binary file contents'
1207
1208 An existing file of the same name is overwritten.
1209
1210 .. versionadded:: 3.5
1211
1212
Максим5f227412020-10-21 05:08:19 +03001213.. method:: Path.write_text(data, encoding=None, errors=None, newline=None)
Georg Brandlea683982014-10-01 19:12:33 +02001214
1215 Open the file pointed to in text mode, write *data* to it, and close the
1216 file::
1217
1218 >>> p = Path('my_text_file')
1219 >>> p.write_text('Text file contents')
1220 18
1221 >>> p.read_text()
1222 'Text file contents'
1223
Lysandros Nikolaouaf636f42019-09-11 18:08:10 +03001224 An existing file of the same name is overwritten. The optional parameters
1225 have the same meaning as in :func:`open`.
1226
Georg Brandlea683982014-10-01 19:12:33 +02001227 .. versionadded:: 3.5
Jamiel Almeidaae8750b2017-06-02 11:36:02 -07001228
Максим5f227412020-10-21 05:08:19 +03001229 .. versionchanged:: 3.10
1230 The *newline* parameter was added.
1231
Jamiel Almeidaae8750b2017-06-02 11:36:02 -07001232Correspondence to tools in the :mod:`os` module
1233-----------------------------------------------
1234
1235Below is a table mapping various :mod:`os` functions to their corresponding
1236:class:`PurePath`/:class:`Path` equivalent.
1237
1238.. note::
1239
Hong Xu1459fed2021-01-20 02:20:00 -08001240 Not all pairs of functions/methods below are equivalent. Some of them,
1241 despite having some overlapping use-cases, have different semantics. They
1242 include :func:`os.path.abspath` and :meth:`Path.resolve`,
1243 :func:`os.path.relpath` and :meth:`PurePath.relative_to`.
Jamiel Almeidaae8750b2017-06-02 11:36:02 -07001244
Xtreak6f9c55d2018-10-05 20:54:11 +05301245==================================== ==============================
Hong Xu1459fed2021-01-20 02:20:00 -08001246:mod:`os` and :mod:`os.path` :mod:`pathlib`
Xtreak6f9c55d2018-10-05 20:54:11 +05301247==================================== ==============================
Hong Xu1459fed2021-01-20 02:20:00 -08001248:func:`os.path.abspath` :meth:`Path.resolve` [#]_
Xtreak6f9c55d2018-10-05 20:54:11 +05301249:func:`os.chmod` :meth:`Path.chmod`
1250:func:`os.mkdir` :meth:`Path.mkdir`
Joannah Nanjekyef25fb6e2020-05-04 16:47:03 -03001251:func:`os.makedirs` :meth:`Path.mkdir`
Xtreak6f9c55d2018-10-05 20:54:11 +05301252:func:`os.rename` :meth:`Path.rename`
1253:func:`os.replace` :meth:`Path.replace`
1254:func:`os.rmdir` :meth:`Path.rmdir`
1255:func:`os.remove`, :func:`os.unlink` :meth:`Path.unlink`
1256:func:`os.getcwd` :func:`Path.cwd`
1257:func:`os.path.exists` :meth:`Path.exists`
1258:func:`os.path.expanduser` :meth:`Path.expanduser` and
1259 :meth:`Path.home`
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)0eb9deb2020-08-14 01:22:04 +05301260:func:`os.listdir` :meth:`Path.iterdir`
Xtreak6f9c55d2018-10-05 20:54:11 +05301261:func:`os.path.isdir` :meth:`Path.is_dir`
1262:func:`os.path.isfile` :meth:`Path.is_file`
1263:func:`os.path.islink` :meth:`Path.is_symlink`
Barney Galef24e2e52021-04-23 21:48:52 +01001264:func:`os.link` :meth:`Path.hardlink_to`
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)0eb9deb2020-08-14 01:22:04 +05301265:func:`os.symlink` :meth:`Path.symlink_to`
Girtsa01ba332019-10-23 14:18:40 -07001266:func:`os.readlink` :meth:`Path.readlink`
Hong Xu1459fed2021-01-20 02:20:00 -08001267:func:`os.path.relpath` :meth:`Path.relative_to` [#]_
Xtreak6f9c55d2018-10-05 20:54:11 +05301268:func:`os.stat` :meth:`Path.stat`,
1269 :meth:`Path.owner`,
1270 :meth:`Path.group`
1271:func:`os.path.isabs` :meth:`PurePath.is_absolute`
1272:func:`os.path.join` :func:`PurePath.joinpath`
1273:func:`os.path.basename` :data:`PurePath.name`
1274:func:`os.path.dirname` :data:`PurePath.parent`
1275:func:`os.path.samefile` :meth:`Path.samefile`
1276:func:`os.path.splitext` :data:`PurePath.suffix`
1277==================================== ==============================
Hong Xu1459fed2021-01-20 02:20:00 -08001278
1279.. rubric:: Footnotes
1280
1281.. [#] :func:`os.path.abspath` does not resolve symbolic links while :meth:`Path.resolve` does.
1282.. [#] :meth:`Path.relative_to` requires ``self`` to be the subpath of the argument, but :func:`os.path.relpath` does not.