pathlib

Object-oriented filesystem paths.

This module provides classes to represent abstract paths and concrete paths with operations that have semantics appropriate for different operating systems.

 1"""Object-oriented filesystem paths.
 2
 3This module provides classes to represent abstract paths and concrete
 4paths with operations that have semantics appropriate for different
 5operating systems.
 6"""
 7
 8from ._abc import *
 9from ._local import *
10
11__all__ = (_abc.__all__ +
12           _local.__all__)
class UnsupportedOperation(builtins.NotImplementedError):
49class UnsupportedOperation(NotImplementedError):
50    """An exception that is raised when an unsupported operation is called on
51    a path object.
52    """
53    pass

An exception that is raised when an unsupported operation is called on a path object.

Inherited Members
builtins.NotImplementedError
NotImplementedError
builtins.BaseException
with_traceback
add_note
args
class PurePath(pathlib._abc.PurePathBase):
 60class PurePath(PurePathBase):
 61    """Base class for manipulating paths without I/O.
 62
 63    PurePath represents a filesystem path and offers operations which
 64    don't imply any actual filesystem I/O.  Depending on your system,
 65    instantiating a PurePath will return either a PurePosixPath or a
 66    PureWindowsPath object.  You can also instantiate either of these classes
 67    directly, regardless of your system.
 68    """
 69
 70    __slots__ = (
 71        # The `_raw_paths` slot stores unnormalized string paths. This is set
 72        # in the `__init__()` method.
 73        '_raw_paths',
 74
 75        # The `_drv`, `_root` and `_tail_cached` slots store parsed and
 76        # normalized parts of the path. They are set when any of the `drive`,
 77        # `root` or `_tail` properties are accessed for the first time. The
 78        # three-part division corresponds to the result of
 79        # `os.path.splitroot()`, except that the tail is further split on path
 80        # separators (i.e. it is a list of strings), and that the root and
 81        # tail are normalized.
 82        '_drv', '_root', '_tail_cached',
 83
 84        # The `_str` slot stores the string representation of the path,
 85        # computed from the drive, root and tail when `__str__()` is called
 86        # for the first time. It's used to implement `_str_normcase`
 87        '_str',
 88
 89        # The `_str_normcase_cached` slot stores the string path with
 90        # normalized case. It is set when the `_str_normcase` property is
 91        # accessed for the first time. It's used to implement `__eq__()`
 92        # `__hash__()`, and `_parts_normcase`
 93        '_str_normcase_cached',
 94
 95        # The `_parts_normcase_cached` slot stores the case-normalized
 96        # string path after splitting on path separators. It's set when the
 97        # `_parts_normcase` property is accessed for the first time. It's used
 98        # to implement comparison methods like `__lt__()`.
 99        '_parts_normcase_cached',
100
101        # The `_hash` slot stores the hash of the case-normalized string
102        # path. It's set when `__hash__()` is called for the first time.
103        '_hash',
104    )
105    parser = os.path
106    _globber = _StringGlobber
107
108    def __new__(cls, *args, **kwargs):
109        """Construct a PurePath from one or several strings and or existing
110        PurePath objects.  The strings and path objects are combined so as
111        to yield a canonicalized path, which is incorporated into the
112        new PurePath object.
113        """
114        if cls is PurePath:
115            cls = PureWindowsPath if os.name == 'nt' else PurePosixPath
116        return object.__new__(cls)
117
118    def __init__(self, *args):
119        paths = []
120        for arg in args:
121            if isinstance(arg, PurePath):
122                if arg.parser is not self.parser:
123                    # GH-103631: Convert separators for backwards compatibility.
124                    paths.append(arg.as_posix())
125                else:
126                    paths.extend(arg._raw_paths)
127            else:
128                try:
129                    path = os.fspath(arg)
130                except TypeError:
131                    path = arg
132                if not isinstance(path, str):
133                    raise TypeError(
134                        "argument should be a str or an os.PathLike "
135                        "object where __fspath__ returns a str, "
136                        f"not {type(path).__name__!r}")
137                paths.append(path)
138        # Avoid calling super().__init__, as an optimisation
139        self._raw_paths = paths
140
141    def joinpath(self, *pathsegments):
142        """Combine this path with one or several arguments, and return a
143        new path representing either a subpath (if all arguments are relative
144        paths) or a totally different path (if one of the arguments is
145        anchored).
146        """
147        return self.with_segments(self, *pathsegments)
148
149    def __truediv__(self, key):
150        try:
151            return self.with_segments(self, key)
152        except TypeError:
153            return NotImplemented
154
155    def __rtruediv__(self, key):
156        try:
157            return self.with_segments(key, self)
158        except TypeError:
159            return NotImplemented
160
161    def __reduce__(self):
162        return self.__class__, tuple(self._raw_paths)
163
164    def __repr__(self):
165        return "{}({!r})".format(self.__class__.__name__, self.as_posix())
166
167    def __fspath__(self):
168        return str(self)
169
170    def __bytes__(self):
171        """Return the bytes representation of the path.  This is only
172        recommended to use under Unix."""
173        return os.fsencode(self)
174
175    @property
176    def _str_normcase(self):
177        # String with normalized case, for hashing and equality checks
178        try:
179            return self._str_normcase_cached
180        except AttributeError:
181            if self.parser is posixpath:
182                self._str_normcase_cached = str(self)
183            else:
184                self._str_normcase_cached = str(self).lower()
185            return self._str_normcase_cached
186
187    def __hash__(self):
188        try:
189            return self._hash
190        except AttributeError:
191            self._hash = hash(self._str_normcase)
192            return self._hash
193
194    def __eq__(self, other):
195        if not isinstance(other, PurePath):
196            return NotImplemented
197        return self._str_normcase == other._str_normcase and self.parser is other.parser
198
199    @property
200    def _parts_normcase(self):
201        # Cached parts with normalized case, for comparisons.
202        try:
203            return self._parts_normcase_cached
204        except AttributeError:
205            self._parts_normcase_cached = self._str_normcase.split(self.parser.sep)
206            return self._parts_normcase_cached
207
208    def __lt__(self, other):
209        if not isinstance(other, PurePath) or self.parser is not other.parser:
210            return NotImplemented
211        return self._parts_normcase < other._parts_normcase
212
213    def __le__(self, other):
214        if not isinstance(other, PurePath) or self.parser is not other.parser:
215            return NotImplemented
216        return self._parts_normcase <= other._parts_normcase
217
218    def __gt__(self, other):
219        if not isinstance(other, PurePath) or self.parser is not other.parser:
220            return NotImplemented
221        return self._parts_normcase > other._parts_normcase
222
223    def __ge__(self, other):
224        if not isinstance(other, PurePath) or self.parser is not other.parser:
225            return NotImplemented
226        return self._parts_normcase >= other._parts_normcase
227
228    def __str__(self):
229        """Return the string representation of the path, suitable for
230        passing to system calls."""
231        try:
232            return self._str
233        except AttributeError:
234            self._str = self._format_parsed_parts(self.drive, self.root,
235                                                  self._tail) or '.'
236            return self._str
237
238    @classmethod
239    def _format_parsed_parts(cls, drv, root, tail):
240        if drv or root:
241            return drv + root + cls.parser.sep.join(tail)
242        elif tail and cls.parser.splitdrive(tail[0])[0]:
243            tail = ['.'] + tail
244        return cls.parser.sep.join(tail)
245
246    def _from_parsed_parts(self, drv, root, tail):
247        path = self._from_parsed_string(self._format_parsed_parts(drv, root, tail))
248        path._drv = drv
249        path._root = root
250        path._tail_cached = tail
251        return path
252
253    def _from_parsed_string(self, path_str):
254        path = self.with_segments(path_str)
255        path._str = path_str or '.'
256        return path
257
258    @classmethod
259    def _parse_path(cls, path):
260        if not path:
261            return '', '', []
262        sep = cls.parser.sep
263        altsep = cls.parser.altsep
264        if altsep:
265            path = path.replace(altsep, sep)
266        drv, root, rel = cls.parser.splitroot(path)
267        if not root and drv.startswith(sep) and not drv.endswith(sep):
268            drv_parts = drv.split(sep)
269            if len(drv_parts) == 4 and drv_parts[2] not in '?.':
270                # e.g. //server/share
271                root = sep
272            elif len(drv_parts) == 6:
273                # e.g. //?/unc/server/share
274                root = sep
275        parsed = [sys.intern(str(x)) for x in rel.split(sep) if x and x != '.']
276        return drv, root, parsed
277
278    @property
279    def _raw_path(self):
280        """The joined but unnormalized path."""
281        paths = self._raw_paths
282        if len(paths) == 0:
283            path = ''
284        elif len(paths) == 1:
285            path = paths[0]
286        else:
287            path = self.parser.join(*paths)
288        return path
289
290    @property
291    def drive(self):
292        """The drive prefix (letter or UNC path), if any."""
293        try:
294            return self._drv
295        except AttributeError:
296            self._drv, self._root, self._tail_cached = self._parse_path(self._raw_path)
297            return self._drv
298
299    @property
300    def root(self):
301        """The root of the path, if any."""
302        try:
303            return self._root
304        except AttributeError:
305            self._drv, self._root, self._tail_cached = self._parse_path(self._raw_path)
306            return self._root
307
308    @property
309    def _tail(self):
310        try:
311            return self._tail_cached
312        except AttributeError:
313            self._drv, self._root, self._tail_cached = self._parse_path(self._raw_path)
314            return self._tail_cached
315
316    @property
317    def anchor(self):
318        """The concatenation of the drive and root, or ''."""
319        return self.drive + self.root
320
321    @property
322    def parts(self):
323        """An object providing sequence-like access to the
324        components in the filesystem path."""
325        if self.drive or self.root:
326            return (self.drive + self.root,) + tuple(self._tail)
327        else:
328            return tuple(self._tail)
329
330    @property
331    def parent(self):
332        """The logical parent of the path."""
333        drv = self.drive
334        root = self.root
335        tail = self._tail
336        if not tail:
337            return self
338        return self._from_parsed_parts(drv, root, tail[:-1])
339
340    @property
341    def parents(self):
342        """A sequence of this path's logical parents."""
343        # The value of this property should not be cached on the path object,
344        # as doing so would introduce a reference cycle.
345        return _PathParents(self)
346
347    @property
348    def name(self):
349        """The final path component, if any."""
350        tail = self._tail
351        if not tail:
352            return ''
353        return tail[-1]
354
355    def with_name(self, name):
356        """Return a new path with the file name changed."""
357        p = self.parser
358        if not name or p.sep in name or (p.altsep and p.altsep in name) or name == '.':
359            raise ValueError(f"Invalid name {name!r}")
360        tail = self._tail.copy()
361        if not tail:
362            raise ValueError(f"{self!r} has an empty name")
363        tail[-1] = name
364        return self._from_parsed_parts(self.drive, self.root, tail)
365
366    def relative_to(self, other, /, *_deprecated, walk_up=False):
367        """Return the relative path to another path identified by the passed
368        arguments.  If the operation is not possible (because this is not
369        related to the other path), raise ValueError.
370
371        The *walk_up* parameter controls whether `..` may be used to resolve
372        the path.
373        """
374        if _deprecated:
375            msg = ("support for supplying more than one positional argument "
376                   "to pathlib.PurePath.relative_to() is deprecated and "
377                   "scheduled for removal in Python 3.14")
378            warnings.warn(msg, DeprecationWarning, stacklevel=2)
379            other = self.with_segments(other, *_deprecated)
380        elif not isinstance(other, PurePath):
381            other = self.with_segments(other)
382        for step, path in enumerate(chain([other], other.parents)):
383            if path == self or path in self.parents:
384                break
385            elif not walk_up:
386                raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
387            elif path.name == '..':
388                raise ValueError(f"'..' segment in {str(other)!r} cannot be walked")
389        else:
390            raise ValueError(f"{str(self)!r} and {str(other)!r} have different anchors")
391        parts = ['..'] * step + self._tail[len(path._tail):]
392        return self._from_parsed_parts('', '', parts)
393
394    def is_relative_to(self, other, /, *_deprecated):
395        """Return True if the path is relative to another path or False.
396        """
397        if _deprecated:
398            msg = ("support for supplying more than one argument to "
399                   "pathlib.PurePath.is_relative_to() is deprecated and "
400                   "scheduled for removal in Python 3.14")
401            warnings.warn(msg, DeprecationWarning, stacklevel=2)
402            other = self.with_segments(other, *_deprecated)
403        elif not isinstance(other, PurePath):
404            other = self.with_segments(other)
405        return other == self or other in self.parents
406
407    def is_absolute(self):
408        """True if the path is absolute (has both a root and, if applicable,
409        a drive)."""
410        if self.parser is posixpath:
411            # Optimization: work with raw paths on POSIX.
412            for path in self._raw_paths:
413                if path.startswith('/'):
414                    return True
415            return False
416        return self.parser.isabs(self)
417
418    def is_reserved(self):
419        """Return True if the path contains one of the special names reserved
420        by the system, if any."""
421        msg = ("pathlib.PurePath.is_reserved() is deprecated and scheduled "
422               "for removal in Python 3.15. Use os.path.isreserved() to "
423               "detect reserved paths on Windows.")
424        warnings.warn(msg, DeprecationWarning, stacklevel=2)
425        if self.parser is ntpath:
426            return self.parser.isreserved(self)
427        return False
428
429    def as_uri(self):
430        """Return the path as a URI."""
431        if not self.is_absolute():
432            raise ValueError("relative path can't be expressed as a file URI")
433
434        drive = self.drive
435        if len(drive) == 2 and drive[1] == ':':
436            # It's a path on a local drive => 'file:///c:/a/b'
437            prefix = 'file:///' + drive
438            path = self.as_posix()[2:]
439        elif drive:
440            # It's a path on a network drive => 'file://host/share/a/b'
441            prefix = 'file:'
442            path = self.as_posix()
443        else:
444            # It's a posix path => 'file:///etc/hosts'
445            prefix = 'file://'
446            path = str(self)
447        from urllib.parse import quote_from_bytes
448        return prefix + quote_from_bytes(os.fsencode(path))
449
450    @property
451    def _pattern_str(self):
452        """The path expressed as a string, for use in pattern-matching."""
453        # The string representation of an empty path is a single dot ('.'). Empty
454        # paths shouldn't match wildcards, so we change it to the empty string.
455        path_str = str(self)
456        return '' if path_str == '.' else path_str

Base class for manipulating paths without I/O.

PurePath represents a filesystem path and offers operations which don't imply any actual filesystem I/O. Depending on your system, instantiating a PurePath will return either a PurePosixPath or a PureWindowsPath object. You can also instantiate either of these classes directly, regardless of your system.

PurePath(*args, **kwargs)
108    def __new__(cls, *args, **kwargs):
109        """Construct a PurePath from one or several strings and or existing
110        PurePath objects.  The strings and path objects are combined so as
111        to yield a canonicalized path, which is incorporated into the
112        new PurePath object.
113        """
114        if cls is PurePath:
115            cls = PureWindowsPath if os.name == 'nt' else PurePosixPath
116        return object.__new__(cls)

Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object.

def joinpath(self, *pathsegments):
141    def joinpath(self, *pathsegments):
142        """Combine this path with one or several arguments, and return a
143        new path representing either a subpath (if all arguments are relative
144        paths) or a totally different path (if one of the arguments is
145        anchored).
146        """
147        return self.with_segments(self, *pathsegments)

Combine this path with one or several arguments, and return a new path representing either a subpath (if all arguments are relative paths) or a totally different path (if one of the arguments is anchored).

drive
290    @property
291    def drive(self):
292        """The drive prefix (letter or UNC path), if any."""
293        try:
294            return self._drv
295        except AttributeError:
296            self._drv, self._root, self._tail_cached = self._parse_path(self._raw_path)
297            return self._drv

The drive prefix (letter or UNC path), if any.

root
299    @property
300    def root(self):
301        """The root of the path, if any."""
302        try:
303            return self._root
304        except AttributeError:
305            self._drv, self._root, self._tail_cached = self._parse_path(self._raw_path)
306            return self._root

The root of the path, if any.

anchor
316    @property
317    def anchor(self):
318        """The concatenation of the drive and root, or ''."""
319        return self.drive + self.root

The concatenation of the drive and root, or ''.

parts
321    @property
322    def parts(self):
323        """An object providing sequence-like access to the
324        components in the filesystem path."""
325        if self.drive or self.root:
326            return (self.drive + self.root,) + tuple(self._tail)
327        else:
328            return tuple(self._tail)

An object providing sequence-like access to the components in the filesystem path.

parent
330    @property
331    def parent(self):
332        """The logical parent of the path."""
333        drv = self.drive
334        root = self.root
335        tail = self._tail
336        if not tail:
337            return self
338        return self._from_parsed_parts(drv, root, tail[:-1])

The logical parent of the path.

parents
340    @property
341    def parents(self):
342        """A sequence of this path's logical parents."""
343        # The value of this property should not be cached on the path object,
344        # as doing so would introduce a reference cycle.
345        return _PathParents(self)

A sequence of this path's logical parents.

name
347    @property
348    def name(self):
349        """The final path component, if any."""
350        tail = self._tail
351        if not tail:
352            return ''
353        return tail[-1]

The final path component, if any.

def with_name(self, name):
355    def with_name(self, name):
356        """Return a new path with the file name changed."""
357        p = self.parser
358        if not name or p.sep in name or (p.altsep and p.altsep in name) or name == '.':
359            raise ValueError(f"Invalid name {name!r}")
360        tail = self._tail.copy()
361        if not tail:
362            raise ValueError(f"{self!r} has an empty name")
363        tail[-1] = name
364        return self._from_parsed_parts(self.drive, self.root, tail)

Return a new path with the file name changed.

def relative_to(self, other, /, *_deprecated, walk_up=False):
366    def relative_to(self, other, /, *_deprecated, walk_up=False):
367        """Return the relative path to another path identified by the passed
368        arguments.  If the operation is not possible (because this is not
369        related to the other path), raise ValueError.
370
371        The *walk_up* parameter controls whether `..` may be used to resolve
372        the path.
373        """
374        if _deprecated:
375            msg = ("support for supplying more than one positional argument "
376                   "to pathlib.PurePath.relative_to() is deprecated and "
377                   "scheduled for removal in Python 3.14")
378            warnings.warn(msg, DeprecationWarning, stacklevel=2)
379            other = self.with_segments(other, *_deprecated)
380        elif not isinstance(other, PurePath):
381            other = self.with_segments(other)
382        for step, path in enumerate(chain([other], other.parents)):
383            if path == self or path in self.parents:
384                break
385            elif not walk_up:
386                raise ValueError(f"{str(self)!r} is not in the subpath of {str(other)!r}")
387            elif path.name == '..':
388                raise ValueError(f"'..' segment in {str(other)!r} cannot be walked")
389        else:
390            raise ValueError(f"{str(self)!r} and {str(other)!r} have different anchors")
391        parts = ['..'] * step + self._tail[len(path._tail):]
392        return self._from_parsed_parts('', '', parts)

Return the relative path to another path identified by the passed arguments. If the operation is not possible (because this is not related to the other path), raise ValueError.

The walk_up parameter controls whether .. may be used to resolve the path.

def is_relative_to(self, other, /, *_deprecated):
394    def is_relative_to(self, other, /, *_deprecated):
395        """Return True if the path is relative to another path or False.
396        """
397        if _deprecated:
398            msg = ("support for supplying more than one argument to "
399                   "pathlib.PurePath.is_relative_to() is deprecated and "
400                   "scheduled for removal in Python 3.14")
401            warnings.warn(msg, DeprecationWarning, stacklevel=2)
402            other = self.with_segments(other, *_deprecated)
403        elif not isinstance(other, PurePath):
404            other = self.with_segments(other)
405        return other == self or other in self.parents

Return True if the path is relative to another path or False.

def is_absolute(self):
407    def is_absolute(self):
408        """True if the path is absolute (has both a root and, if applicable,
409        a drive)."""
410        if self.parser is posixpath:
411            # Optimization: work with raw paths on POSIX.
412            for path in self._raw_paths:
413                if path.startswith('/'):
414                    return True
415            return False
416        return self.parser.isabs(self)

True if the path is absolute (has both a root and, if applicable, a drive).

def is_reserved(self):
418    def is_reserved(self):
419        """Return True if the path contains one of the special names reserved
420        by the system, if any."""
421        msg = ("pathlib.PurePath.is_reserved() is deprecated and scheduled "
422               "for removal in Python 3.15. Use os.path.isreserved() to "
423               "detect reserved paths on Windows.")
424        warnings.warn(msg, DeprecationWarning, stacklevel=2)
425        if self.parser is ntpath:
426            return self.parser.isreserved(self)
427        return False

Return True if the path contains one of the special names reserved by the system, if any.

def as_uri(self):
429    def as_uri(self):
430        """Return the path as a URI."""
431        if not self.is_absolute():
432            raise ValueError("relative path can't be expressed as a file URI")
433
434        drive = self.drive
435        if len(drive) == 2 and drive[1] == ':':
436            # It's a path on a local drive => 'file:///c:/a/b'
437            prefix = 'file:///' + drive
438            path = self.as_posix()[2:]
439        elif drive:
440            # It's a path on a network drive => 'file://host/share/a/b'
441            prefix = 'file:'
442            path = self.as_posix()
443        else:
444            # It's a posix path => 'file:///etc/hosts'
445            prefix = 'file://'
446            path = str(self)
447        from urllib.parse import quote_from_bytes
448        return prefix + quote_from_bytes(os.fsencode(path))

Return the path as a URI.

Inherited Members
pathlib._abc.PurePathBase
with_segments
as_posix
suffix
suffixes
stem
with_stem
with_suffix
match
full_match
class PurePosixPath(pathlib.PurePath):
463class PurePosixPath(PurePath):
464    """PurePath subclass for non-Windows systems.
465
466    On a POSIX system, instantiating a PurePath should return this object.
467    However, you can also instantiate it directly on any system.
468    """
469    parser = posixpath
470    __slots__ = ()

PurePath subclass for non-Windows systems.

On a POSIX system, instantiating a PurePath should return this object. However, you can also instantiate it directly on any system.

Inherited Members
PurePath
PurePath
joinpath
drive
root
anchor
parts
parent
parents
name
with_name
relative_to
is_relative_to
is_absolute
is_reserved
as_uri
pathlib._abc.PurePathBase
with_segments
as_posix
suffix
suffixes
stem
with_stem
with_suffix
match
full_match
class PureWindowsPath(pathlib.PurePath):
473class PureWindowsPath(PurePath):
474    """PurePath subclass for Windows systems.
475
476    On a Windows system, instantiating a PurePath should return this object.
477    However, you can also instantiate it directly on any system.
478    """
479    parser = ntpath
480    __slots__ = ()

PurePath subclass for Windows systems.

On a Windows system, instantiating a PurePath should return this object. However, you can also instantiate it directly on any system.

Inherited Members
PurePath
PurePath
joinpath
drive
root
anchor
parts
parent
parents
name
with_name
relative_to
is_relative_to
is_absolute
is_reserved
as_uri
pathlib._abc.PurePathBase
with_segments
as_posix
suffix
suffixes
stem
with_stem
with_suffix
match
full_match
class Path(pathlib._abc.PathBase, pathlib.PurePath):
483class Path(PathBase, PurePath):
484    """PurePath subclass that can make system calls.
485
486    Path represents a filesystem path but unlike PurePath, also offers
487    methods to do system calls on path objects. Depending on your system,
488    instantiating a Path will return either a PosixPath or a WindowsPath
489    object. You can also instantiate a PosixPath or WindowsPath directly,
490    but cannot instantiate a WindowsPath on a POSIX system or vice versa.
491    """
492    __slots__ = ()
493    as_uri = PurePath.as_uri
494
495    @classmethod
496    def _unsupported_msg(cls, attribute):
497        return f"{cls.__name__}.{attribute} is unsupported on this system"
498
499    def __init__(self, *args, **kwargs):
500        if kwargs:
501            msg = ("support for supplying keyword arguments to pathlib.PurePath "
502                   "is deprecated and scheduled for removal in Python {remove}")
503            warnings._deprecated("pathlib.PurePath(**kwargs)", msg, remove=(3, 14))
504        super().__init__(*args)
505
506    def __new__(cls, *args, **kwargs):
507        if cls is Path:
508            cls = WindowsPath if os.name == 'nt' else PosixPath
509        return object.__new__(cls)
510
511    def stat(self, *, follow_symlinks=True):
512        """
513        Return the result of the stat() system call on this path, like
514        os.stat() does.
515        """
516        return os.stat(self, follow_symlinks=follow_symlinks)
517
518    def is_mount(self):
519        """
520        Check if this path is a mount point
521        """
522        return os.path.ismount(self)
523
524    def is_junction(self):
525        """
526        Whether this path is a junction.
527        """
528        return os.path.isjunction(self)
529
530    def open(self, mode='r', buffering=-1, encoding=None,
531             errors=None, newline=None):
532        """
533        Open the file pointed to by this path and return a file object, as
534        the built-in open() function does.
535        """
536        if "b" not in mode:
537            encoding = io.text_encoding(encoding)
538        return io.open(self, mode, buffering, encoding, errors, newline)
539
540    def read_text(self, encoding=None, errors=None, newline=None):
541        """
542        Open the file in text mode, read it, and close the file.
543        """
544        # Call io.text_encoding() here to ensure any warning is raised at an
545        # appropriate stack level.
546        encoding = io.text_encoding(encoding)
547        return PathBase.read_text(self, encoding, errors, newline)
548
549    def write_text(self, data, encoding=None, errors=None, newline=None):
550        """
551        Open the file in text mode, write to it, and close the file.
552        """
553        # Call io.text_encoding() here to ensure any warning is raised at an
554        # appropriate stack level.
555        encoding = io.text_encoding(encoding)
556        return PathBase.write_text(self, data, encoding, errors, newline)
557
558    _remove_leading_dot = operator.itemgetter(slice(2, None))
559    _remove_trailing_slash = operator.itemgetter(slice(-1))
560
561    def _filter_trailing_slash(self, paths):
562        sep = self.parser.sep
563        anchor_len = len(self.anchor)
564        for path_str in paths:
565            if len(path_str) > anchor_len and path_str[-1] == sep:
566                path_str = path_str[:-1]
567            yield path_str
568
569    def iterdir(self):
570        """Yield path objects of the directory contents.
571
572        The children are yielded in arbitrary order, and the
573        special entries '.' and '..' are not included.
574        """
575        root_dir = str(self)
576        with os.scandir(root_dir) as scandir_it:
577            paths = [entry.path for entry in scandir_it]
578        if root_dir == '.':
579            paths = map(self._remove_leading_dot, paths)
580        return map(self._from_parsed_string, paths)
581
582    def glob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
583        """Iterate over this subtree and yield all existing files (of any
584        kind, including directories) matching the given relative pattern.
585        """
586        sys.audit("pathlib.Path.glob", self, pattern)
587        if not isinstance(pattern, PurePath):
588            pattern = self.with_segments(pattern)
589        if pattern.anchor:
590            raise NotImplementedError("Non-relative patterns are unsupported")
591        parts = pattern._tail.copy()
592        if not parts:
593            raise ValueError("Unacceptable pattern: {!r}".format(pattern))
594        raw = pattern._raw_path
595        if raw[-1] in (self.parser.sep, self.parser.altsep):
596            # GH-65238: pathlib doesn't preserve trailing slash. Add it back.
597            parts.append('')
598        select = self._glob_selector(parts[::-1], case_sensitive, recurse_symlinks)
599        root = str(self)
600        paths = select(root)
601
602        # Normalize results
603        if root == '.':
604            paths = map(self._remove_leading_dot, paths)
605        if parts[-1] == '':
606            paths = map(self._remove_trailing_slash, paths)
607        elif parts[-1] == '**':
608            paths = self._filter_trailing_slash(paths)
609        paths = map(self._from_parsed_string, paths)
610        return paths
611
612    def rglob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
613        """Recursively yield all existing files (of any kind, including
614        directories) matching the given relative pattern, anywhere in
615        this subtree.
616        """
617        sys.audit("pathlib.Path.rglob", self, pattern)
618        if not isinstance(pattern, PurePath):
619            pattern = self.with_segments(pattern)
620        pattern = '**' / pattern
621        return self.glob(pattern, case_sensitive=case_sensitive, recurse_symlinks=recurse_symlinks)
622
623    def walk(self, top_down=True, on_error=None, follow_symlinks=False):
624        """Walk the directory tree from this directory, similar to os.walk()."""
625        sys.audit("pathlib.Path.walk", self, on_error, follow_symlinks)
626        root_dir = str(self)
627        if not follow_symlinks:
628            follow_symlinks = os._walk_symlinks_as_files
629        results = os.walk(root_dir, top_down, on_error, follow_symlinks)
630        for path_str, dirnames, filenames in results:
631            if root_dir == '.':
632                path_str = path_str[2:]
633            yield self._from_parsed_string(path_str), dirnames, filenames
634
635    def absolute(self):
636        """Return an absolute version of this path
637        No normalization or symlink resolution is performed.
638
639        Use resolve() to resolve symlinks and remove '..' segments.
640        """
641        if self.is_absolute():
642            return self
643        if self.root:
644            drive = os.path.splitroot(os.getcwd())[0]
645            return self._from_parsed_parts(drive, self.root, self._tail)
646        if self.drive:
647            # There is a CWD on each drive-letter drive.
648            cwd = os.path.abspath(self.drive)
649        else:
650            cwd = os.getcwd()
651        if not self._tail:
652            # Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
653            # We pass only one argument to with_segments() to avoid the cost
654            # of joining, and we exploit the fact that getcwd() returns a
655            # fully-normalized string by storing it in _str. This is used to
656            # implement Path.cwd().
657            return self._from_parsed_string(cwd)
658        drive, root, rel = os.path.splitroot(cwd)
659        if not rel:
660            return self._from_parsed_parts(drive, root, self._tail)
661        tail = rel.split(self.parser.sep)
662        tail.extend(self._tail)
663        return self._from_parsed_parts(drive, root, tail)
664
665    def resolve(self, strict=False):
666        """
667        Make the path absolute, resolving all symlinks on the way and also
668        normalizing it.
669        """
670
671        return self.with_segments(os.path.realpath(self, strict=strict))
672
673    if pwd:
674        def owner(self, *, follow_symlinks=True):
675            """
676            Return the login name of the file owner.
677            """
678            uid = self.stat(follow_symlinks=follow_symlinks).st_uid
679            return pwd.getpwuid(uid).pw_name
680
681    if grp:
682        def group(self, *, follow_symlinks=True):
683            """
684            Return the group name of the file gid.
685            """
686            gid = self.stat(follow_symlinks=follow_symlinks).st_gid
687            return grp.getgrgid(gid).gr_name
688
689    if hasattr(os, "readlink"):
690        def readlink(self):
691            """
692            Return the path to which the symbolic link points.
693            """
694            return self.with_segments(os.readlink(self))
695
696    def touch(self, mode=0o666, exist_ok=True):
697        """
698        Create this file with the given access mode, if it doesn't exist.
699        """
700
701        if exist_ok:
702            # First try to bump modification time
703            # Implementation note: GNU touch uses the UTIME_NOW option of
704            # the utimensat() / futimens() functions.
705            try:
706                os.utime(self, None)
707            except OSError:
708                # Avoid exception chaining
709                pass
710            else:
711                return
712        flags = os.O_CREAT | os.O_WRONLY
713        if not exist_ok:
714            flags |= os.O_EXCL
715        fd = os.open(self, flags, mode)
716        os.close(fd)
717
718    def mkdir(self, mode=0o777, parents=False, exist_ok=False):
719        """
720        Create a new directory at this given path.
721        """
722        try:
723            os.mkdir(self, mode)
724        except FileNotFoundError:
725            if not parents or self.parent == self:
726                raise
727            self.parent.mkdir(parents=True, exist_ok=True)
728            self.mkdir(mode, parents=False, exist_ok=exist_ok)
729        except OSError:
730            # Cannot rely on checking for EEXIST, since the operating system
731            # could give priority to other errors like EACCES or EROFS
732            if not exist_ok or not self.is_dir():
733                raise
734
735    def chmod(self, mode, *, follow_symlinks=True):
736        """
737        Change the permissions of the path, like os.chmod().
738        """
739        os.chmod(self, mode, follow_symlinks=follow_symlinks)
740
741    def unlink(self, missing_ok=False):
742        """
743        Remove this file or link.
744        If the path is a directory, use rmdir() instead.
745        """
746        try:
747            os.unlink(self)
748        except FileNotFoundError:
749            if not missing_ok:
750                raise
751
752    def rmdir(self):
753        """
754        Remove this directory.  The directory must be empty.
755        """
756        os.rmdir(self)
757
758    def rename(self, target):
759        """
760        Rename this path to the target path.
761
762        The target path may be absolute or relative. Relative paths are
763        interpreted relative to the current working directory, *not* the
764        directory of the Path object.
765
766        Returns the new Path instance pointing to the target path.
767        """
768        os.rename(self, target)
769        return self.with_segments(target)
770
771    def replace(self, target):
772        """
773        Rename this path to the target path, overwriting if that path exists.
774
775        The target path may be absolute or relative. Relative paths are
776        interpreted relative to the current working directory, *not* the
777        directory of the Path object.
778
779        Returns the new Path instance pointing to the target path.
780        """
781        os.replace(self, target)
782        return self.with_segments(target)
783
784    if hasattr(os, "symlink"):
785        def symlink_to(self, target, target_is_directory=False):
786            """
787            Make this path a symlink pointing to the target path.
788            Note the order of arguments (link, target) is the reverse of os.symlink.
789            """
790            os.symlink(target, self, target_is_directory)
791
792    if hasattr(os, "link"):
793        def hardlink_to(self, target):
794            """
795            Make this path a hard link pointing to the same file as *target*.
796
797            Note the order of arguments (self, target) is the reverse of os.link's.
798            """
799            os.link(target, self)
800
801    def expanduser(self):
802        """ Return a new path with expanded ~ and ~user constructs
803        (as returned by os.path.expanduser)
804        """
805        if (not (self.drive or self.root) and
806            self._tail and self._tail[0][:1] == '~'):
807            homedir = os.path.expanduser(self._tail[0])
808            if homedir[:1] == "~":
809                raise RuntimeError("Could not determine home directory.")
810            drv, root, tail = self._parse_path(homedir)
811            return self._from_parsed_parts(drv, root, tail + self._tail[1:])
812
813        return self
814
815    @classmethod
816    def from_uri(cls, uri):
817        """Return a new path from the given 'file' URI."""
818        if not uri.startswith('file:'):
819            raise ValueError(f"URI does not start with 'file:': {uri!r}")
820        path = uri[5:]
821        if path[:3] == '///':
822            # Remove empty authority
823            path = path[2:]
824        elif path[:12] == '//localhost/':
825            # Remove 'localhost' authority
826            path = path[11:]
827        if path[:3] == '///' or (path[:1] == '/' and path[2:3] in ':|'):
828            # Remove slash before DOS device/UNC path
829            path = path[1:]
830        if path[1:2] == '|':
831            # Replace bar with colon in DOS drive
832            path = path[:1] + ':' + path[2:]
833        from urllib.parse import unquote_to_bytes
834        path = cls(os.fsdecode(unquote_to_bytes(path)))
835        if not path.is_absolute():
836            raise ValueError(f"URI is not absolute: {uri!r}")
837        return path

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

Path(*args, **kwargs)
499    def __init__(self, *args, **kwargs):
500        if kwargs:
501            msg = ("support for supplying keyword arguments to pathlib.PurePath "
502                   "is deprecated and scheduled for removal in Python {remove}")
503            warnings._deprecated("pathlib.PurePath(**kwargs)", msg, remove=(3, 14))
504        super().__init__(*args)
def as_uri(self):
429    def as_uri(self):
430        """Return the path as a URI."""
431        if not self.is_absolute():
432            raise ValueError("relative path can't be expressed as a file URI")
433
434        drive = self.drive
435        if len(drive) == 2 and drive[1] == ':':
436            # It's a path on a local drive => 'file:///c:/a/b'
437            prefix = 'file:///' + drive
438            path = self.as_posix()[2:]
439        elif drive:
440            # It's a path on a network drive => 'file://host/share/a/b'
441            prefix = 'file:'
442            path = self.as_posix()
443        else:
444            # It's a posix path => 'file:///etc/hosts'
445            prefix = 'file://'
446            path = str(self)
447        from urllib.parse import quote_from_bytes
448        return prefix + quote_from_bytes(os.fsencode(path))

Return the path as a URI.

def stat(self, *, follow_symlinks=True):
511    def stat(self, *, follow_symlinks=True):
512        """
513        Return the result of the stat() system call on this path, like
514        os.stat() does.
515        """
516        return os.stat(self, follow_symlinks=follow_symlinks)

Return the result of the stat() system call on this path, like os.stat() does.

def is_mount(self):
518    def is_mount(self):
519        """
520        Check if this path is a mount point
521        """
522        return os.path.ismount(self)

Check if this path is a mount point

def is_junction(self):
524    def is_junction(self):
525        """
526        Whether this path is a junction.
527        """
528        return os.path.isjunction(self)

Whether this path is a junction.

def open( self, mode='r', buffering=-1, encoding=None, errors=None, newline=None):
530    def open(self, mode='r', buffering=-1, encoding=None,
531             errors=None, newline=None):
532        """
533        Open the file pointed to by this path and return a file object, as
534        the built-in open() function does.
535        """
536        if "b" not in mode:
537            encoding = io.text_encoding(encoding)
538        return io.open(self, mode, buffering, encoding, errors, newline)

Open the file pointed to by this path and return a file object, as the built-in open() function does.

def read_text(self, encoding=None, errors=None, newline=None):
540    def read_text(self, encoding=None, errors=None, newline=None):
541        """
542        Open the file in text mode, read it, and close the file.
543        """
544        # Call io.text_encoding() here to ensure any warning is raised at an
545        # appropriate stack level.
546        encoding = io.text_encoding(encoding)
547        return PathBase.read_text(self, encoding, errors, newline)

Open the file in text mode, read it, and close the file.

def write_text(self, data, encoding=None, errors=None, newline=None):
549    def write_text(self, data, encoding=None, errors=None, newline=None):
550        """
551        Open the file in text mode, write to it, and close the file.
552        """
553        # Call io.text_encoding() here to ensure any warning is raised at an
554        # appropriate stack level.
555        encoding = io.text_encoding(encoding)
556        return PathBase.write_text(self, data, encoding, errors, newline)

Open the file in text mode, write to it, and close the file.

def iterdir(self):
569    def iterdir(self):
570        """Yield path objects of the directory contents.
571
572        The children are yielded in arbitrary order, and the
573        special entries '.' and '..' are not included.
574        """
575        root_dir = str(self)
576        with os.scandir(root_dir) as scandir_it:
577            paths = [entry.path for entry in scandir_it]
578        if root_dir == '.':
579            paths = map(self._remove_leading_dot, paths)
580        return map(self._from_parsed_string, paths)

Yield path objects of the directory contents.

The children are yielded in arbitrary order, and the special entries '.' and '..' are not included.

def glob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
582    def glob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
583        """Iterate over this subtree and yield all existing files (of any
584        kind, including directories) matching the given relative pattern.
585        """
586        sys.audit("pathlib.Path.glob", self, pattern)
587        if not isinstance(pattern, PurePath):
588            pattern = self.with_segments(pattern)
589        if pattern.anchor:
590            raise NotImplementedError("Non-relative patterns are unsupported")
591        parts = pattern._tail.copy()
592        if not parts:
593            raise ValueError("Unacceptable pattern: {!r}".format(pattern))
594        raw = pattern._raw_path
595        if raw[-1] in (self.parser.sep, self.parser.altsep):
596            # GH-65238: pathlib doesn't preserve trailing slash. Add it back.
597            parts.append('')
598        select = self._glob_selector(parts[::-1], case_sensitive, recurse_symlinks)
599        root = str(self)
600        paths = select(root)
601
602        # Normalize results
603        if root == '.':
604            paths = map(self._remove_leading_dot, paths)
605        if parts[-1] == '':
606            paths = map(self._remove_trailing_slash, paths)
607        elif parts[-1] == '**':
608            paths = self._filter_trailing_slash(paths)
609        paths = map(self._from_parsed_string, paths)
610        return paths

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

def rglob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
612    def rglob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
613        """Recursively yield all existing files (of any kind, including
614        directories) matching the given relative pattern, anywhere in
615        this subtree.
616        """
617        sys.audit("pathlib.Path.rglob", self, pattern)
618        if not isinstance(pattern, PurePath):
619            pattern = self.with_segments(pattern)
620        pattern = '**' / pattern
621        return self.glob(pattern, case_sensitive=case_sensitive, recurse_symlinks=recurse_symlinks)

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

def walk(self, top_down=True, on_error=None, follow_symlinks=False):
623    def walk(self, top_down=True, on_error=None, follow_symlinks=False):
624        """Walk the directory tree from this directory, similar to os.walk()."""
625        sys.audit("pathlib.Path.walk", self, on_error, follow_symlinks)
626        root_dir = str(self)
627        if not follow_symlinks:
628            follow_symlinks = os._walk_symlinks_as_files
629        results = os.walk(root_dir, top_down, on_error, follow_symlinks)
630        for path_str, dirnames, filenames in results:
631            if root_dir == '.':
632                path_str = path_str[2:]
633            yield self._from_parsed_string(path_str), dirnames, filenames

Walk the directory tree from this directory, similar to os.walk().

def absolute(self):
635    def absolute(self):
636        """Return an absolute version of this path
637        No normalization or symlink resolution is performed.
638
639        Use resolve() to resolve symlinks and remove '..' segments.
640        """
641        if self.is_absolute():
642            return self
643        if self.root:
644            drive = os.path.splitroot(os.getcwd())[0]
645            return self._from_parsed_parts(drive, self.root, self._tail)
646        if self.drive:
647            # There is a CWD on each drive-letter drive.
648            cwd = os.path.abspath(self.drive)
649        else:
650            cwd = os.getcwd()
651        if not self._tail:
652            # Fast path for "empty" paths, e.g. Path("."), Path("") or Path().
653            # We pass only one argument to with_segments() to avoid the cost
654            # of joining, and we exploit the fact that getcwd() returns a
655            # fully-normalized string by storing it in _str. This is used to
656            # implement Path.cwd().
657            return self._from_parsed_string(cwd)
658        drive, root, rel = os.path.splitroot(cwd)
659        if not rel:
660            return self._from_parsed_parts(drive, root, self._tail)
661        tail = rel.split(self.parser.sep)
662        tail.extend(self._tail)
663        return self._from_parsed_parts(drive, root, tail)

Return an absolute version of this path No normalization or symlink resolution is performed.

Use resolve() to resolve symlinks and remove '..' segments.

def resolve(self, strict=False):
665    def resolve(self, strict=False):
666        """
667        Make the path absolute, resolving all symlinks on the way and also
668        normalizing it.
669        """
670
671        return self.with_segments(os.path.realpath(self, strict=strict))

Make the path absolute, resolving all symlinks on the way and also normalizing it.

def touch(self, mode=438, exist_ok=True):
696    def touch(self, mode=0o666, exist_ok=True):
697        """
698        Create this file with the given access mode, if it doesn't exist.
699        """
700
701        if exist_ok:
702            # First try to bump modification time
703            # Implementation note: GNU touch uses the UTIME_NOW option of
704            # the utimensat() / futimens() functions.
705            try:
706                os.utime(self, None)
707            except OSError:
708                # Avoid exception chaining
709                pass
710            else:
711                return
712        flags = os.O_CREAT | os.O_WRONLY
713        if not exist_ok:
714            flags |= os.O_EXCL
715        fd = os.open(self, flags, mode)
716        os.close(fd)

Create this file with the given access mode, if it doesn't exist.

def mkdir(self, mode=511, parents=False, exist_ok=False):
718    def mkdir(self, mode=0o777, parents=False, exist_ok=False):
719        """
720        Create a new directory at this given path.
721        """
722        try:
723            os.mkdir(self, mode)
724        except FileNotFoundError:
725            if not parents or self.parent == self:
726                raise
727            self.parent.mkdir(parents=True, exist_ok=True)
728            self.mkdir(mode, parents=False, exist_ok=exist_ok)
729        except OSError:
730            # Cannot rely on checking for EEXIST, since the operating system
731            # could give priority to other errors like EACCES or EROFS
732            if not exist_ok or not self.is_dir():
733                raise

Create a new directory at this given path.

def chmod(self, mode, *, follow_symlinks=True):
735    def chmod(self, mode, *, follow_symlinks=True):
736        """
737        Change the permissions of the path, like os.chmod().
738        """
739        os.chmod(self, mode, follow_symlinks=follow_symlinks)

Change the permissions of the path, like os.chmod().

def rmdir(self):
752    def rmdir(self):
753        """
754        Remove this directory.  The directory must be empty.
755        """
756        os.rmdir(self)

Remove this directory. The directory must be empty.

def rename(self, target):
758    def rename(self, target):
759        """
760        Rename this path to the target path.
761
762        The target path may be absolute or relative. Relative paths are
763        interpreted relative to the current working directory, *not* the
764        directory of the Path object.
765
766        Returns the new Path instance pointing to the target path.
767        """
768        os.rename(self, target)
769        return self.with_segments(target)

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

def replace(self, target):
771    def replace(self, target):
772        """
773        Rename this path to the target path, overwriting if that path exists.
774
775        The target path may be absolute or relative. Relative paths are
776        interpreted relative to the current working directory, *not* the
777        directory of the Path object.
778
779        Returns the new Path instance pointing to the target path.
780        """
781        os.replace(self, target)
782        return self.with_segments(target)

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

def expanduser(self):
801    def expanduser(self):
802        """ Return a new path with expanded ~ and ~user constructs
803        (as returned by os.path.expanduser)
804        """
805        if (not (self.drive or self.root) and
806            self._tail and self._tail[0][:1] == '~'):
807            homedir = os.path.expanduser(self._tail[0])
808            if homedir[:1] == "~":
809                raise RuntimeError("Could not determine home directory.")
810            drv, root, tail = self._parse_path(homedir)
811            return self._from_parsed_parts(drv, root, tail + self._tail[1:])
812
813        return self

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

@classmethod
def from_uri(cls, uri):
815    @classmethod
816    def from_uri(cls, uri):
817        """Return a new path from the given 'file' URI."""
818        if not uri.startswith('file:'):
819            raise ValueError(f"URI does not start with 'file:': {uri!r}")
820        path = uri[5:]
821        if path[:3] == '///':
822            # Remove empty authority
823            path = path[2:]
824        elif path[:12] == '//localhost/':
825            # Remove 'localhost' authority
826            path = path[11:]
827        if path[:3] == '///' or (path[:1] == '/' and path[2:3] in ':|'):
828            # Remove slash before DOS device/UNC path
829            path = path[1:]
830        if path[1:2] == '|':
831            # Replace bar with colon in DOS drive
832            path = path[:1] + ':' + path[2:]
833        from urllib.parse import unquote_to_bytes
834        path = cls(os.fsdecode(unquote_to_bytes(path)))
835        if not path.is_absolute():
836            raise ValueError(f"URI is not absolute: {uri!r}")
837        return path

Return a new path from the given 'file' URI.

def owner(self, *, follow_symlinks=True):
674        def owner(self, *, follow_symlinks=True):
675            """
676            Return the login name of the file owner.
677            """
678            uid = self.stat(follow_symlinks=follow_symlinks).st_uid
679            return pwd.getpwuid(uid).pw_name

Return the login name of the file owner.

def group(self, *, follow_symlinks=True):
682        def group(self, *, follow_symlinks=True):
683            """
684            Return the group name of the file gid.
685            """
686            gid = self.stat(follow_symlinks=follow_symlinks).st_gid
687            return grp.getgrgid(gid).gr_name

Return the group name of the file gid.

Inherited Members
pathlib._abc.PathBase
lstat
exists
is_dir
is_file
is_block_device
is_char_device
is_fifo
is_socket
samefile
read_bytes
write_bytes
cwd
home
lchmod
PurePath
joinpath
drive
root
anchor
parts
parent
parents
name
with_name
relative_to
is_relative_to
is_absolute
is_reserved
pathlib._abc.PurePathBase
with_segments
as_posix
suffix
suffixes
stem
with_stem
with_suffix
match
full_match
class PosixPath(pathlib.Path, pathlib.PurePosixPath):
840class PosixPath(Path, PurePosixPath):
841    """Path subclass for non-Windows systems.
842
843    On a POSIX system, instantiating a Path should return this object.
844    """
845    __slots__ = ()
846
847    if os.name == 'nt':
848        def __new__(cls, *args, **kwargs):
849            raise UnsupportedOperation(
850                f"cannot instantiate {cls.__name__!r} on your system")

Path subclass for non-Windows systems.

On a POSIX system, instantiating a Path should return this object.

Inherited Members
Path
Path
as_uri
stat
is_mount
is_junction
open
read_text
write_text
iterdir
glob
rglob
walk
absolute
resolve
touch
mkdir
chmod
rmdir
rename
replace
expanduser
from_uri
owner
group
pathlib._abc.PathBase
lstat
exists
is_dir
is_file
is_block_device
is_char_device
is_fifo
is_socket
samefile
read_bytes
write_bytes
cwd
home
lchmod
PurePath
joinpath
drive
root
anchor
parts
parent
parents
name
with_name
relative_to
is_relative_to
is_absolute
is_reserved
pathlib._abc.PurePathBase
with_segments
as_posix
suffix
suffixes
stem
with_stem
with_suffix
match
full_match
class WindowsPath(pathlib.Path, pathlib.PureWindowsPath):
852class WindowsPath(Path, PureWindowsPath):
853    """Path subclass for Windows systems.
854
855    On a Windows system, instantiating a Path should return this object.
856    """
857    __slots__ = ()
858
859    if os.name != 'nt':
860        def __new__(cls, *args, **kwargs):
861            raise UnsupportedOperation(
862                f"cannot instantiate {cls.__name__!r} on your system")

Path subclass for Windows systems.

On a Windows system, instantiating a Path should return this object.

Inherited Members
Path
Path
as_uri
stat
is_mount
is_junction
open
read_text
write_text
iterdir
glob
rglob
walk
absolute
resolve
touch
mkdir
chmod
rmdir
rename
replace
expanduser
from_uri
owner
group
pathlib._abc.PathBase
lstat
exists
is_dir
is_file
is_block_device
is_char_device
is_fifo
is_socket
samefile
read_bytes
write_bytes
cwd
home
lchmod
PurePath
joinpath
drive
root
anchor
parts
parent
parents
name
with_name
relative_to
is_relative_to
is_absolute
is_reserved
pathlib._abc.PurePathBase
with_segments
as_posix
suffix
suffixes
stem
with_stem
with_suffix
match
full_match