pathlib / docs / index.rst


Manipulating filesystem paths as string objects can quickly become cumbersome: multiple calls to :func:`os.path.join` or :func:`os.path.dirname`, etc. This module offers a set of classes featuring all the common operations on paths in an easy, object-oriented way.

This module is best used with Python 3.2 or later, but it is also compatible with Python 2.7.


This module has been included in the Python 3.4 standard library after PEP 428 acceptance. You only need to install it for Python 3.3 or older.


Standalone releases are available on PyPI:

Main development now takes place in the Python standard library: see the Python developer's guide.

The maintenance repository for this standalone backport module can be found on BitBucket, but activity is expected to be quite low:

High-level view

This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between :ref:`pure paths <pure-paths>`, which provide purely computational operations without I/O, and :ref:`concrete paths <concrete-paths>`, which inherit from pure paths but also provide I/O operations.


If you've never used this module before or just aren't sure which class is right for your task, :class:`Path` is most likely what you need. It instantiates a :ref:`concrete path <concrete-paths>` for the platform the code is running on.

Pure paths are useful in some special cases; for example:

  1. If you want to manipulate Windows paths on a Unix machine (or vice versa). You cannot instantiate a :class:`WindowsPath` when running on Unix, but you can instantiate :class:`PureWindowsPath`.
  2. You want to make sure that your code only manipulates paths without actually accessing the OS. In this case, instantiating one of the pure classes may be useful since those simply don't have any OS-accessing operations.

Basic use

Importing the module classes:

>>> from pathlib import *

Listing subdirectories:

>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
 PosixPath('__pycache__'), PosixPath('build')]

Listing Python source files in this directory tree:

>>> list(p.glob('**/*.py'))
[PosixPath(''), PosixPath(''),
 PosixPath(''), PosixPath('docs/'),

Navigating inside a directory tree:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
>>> q.resolve()

Querying path properties:

>>> q.exists()
>>> q.is_dir()

Opening a file:

>>> with as f: f.readline()

Pure paths

Pure path objects provide path-handling operations which don't actually access a filesystem. There are three ways to access these classes, which we also call flavours:

A generic class that represents the system's path flavour (instantiating it creates either a :class:`PurePosixPath` or a :class:`PureWindowsPath`):

>>> PurePath('')      # Running on a Unix machine

Each element of pathsegments can be either a string or bytes object representing a path segment; it can also be another path object:

>>> PurePath('foo', 'some/path', 'bar')
>>> PurePath(Path('foo'), Path('bar'))

When pathsegments is empty, the current directory is assumed:

>>> PurePath()

When several absolute paths are given, the last is taken as an anchor (mimicking :func:`os.path.join`'s behaviour):

>>> PurePath('/etc', '/usr', 'lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')

However, in a Windows path, changing the local root doesn't discard the previous drive setting:

>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')

Spurious slashes and single dots are collapsed, but double dots ('..') are not, since this would change the meaning of a path in the face of symbolic links:

>>> PurePath('foo//bar')
>>> PurePath('foo/./bar')
>>> PurePath('foo/../bar')

(a naïve approach would make PurePosixPath('foo/../bar') equivalent to PurePosixPath('bar'), which is wrong if foo is a symbolic link to another directory)

A subclass of :class:`PurePath`, this path flavour represents non-Windows filesystem paths:

>>> PurePosixPath('/etc')

pathsegments is specified similarly to :class:`PurePath`.

A subclass of :class:`PurePath`, this path flavour represents Windows filesystem paths:

>>> PureWindowsPath('c:/Program Files/')
PureWindowsPath('c:/Program Files')

pathsegments is specified similarly to :class:`PurePath`.

Regardless of the system you're running on, you can instantiate all of these classes, since they don't provide any operation that does system calls.

General properties

Paths are immutable and hashable. Paths of a same flavour are comparable and orderable. These properties respect the flavour's case-folding semantics:

>>> PurePosixPath('foo') == PurePosixPath('FOO')
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
>>> PureWindowsPath('C:') < PureWindowsPath('d:')

Paths of a different flavour compare unequal and cannot be ordered:

>>> PureWindowsPath('foo') == PurePosixPath('foo')
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: PureWindowsPath() < PurePosixPath()


The slash operator helps create child paths, similarly to os.path.join:

>>> p = PurePath('/etc')
>>> p
>>> p / 'init.d' / 'apache2'
>>> q = PurePath('bin')
>>> '/usr' / q

The string representation of a path is the raw filesystem path itself (in native form, e.g. with backslashes under Windows), which you can pass to any function taking a file path as a string:

>>> p = PurePath('/etc')
>>> str(p)
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'

Similarly, calling bytes on a path gives the raw filesystem path as a bytes object, as encoded by os.fsencode:

>>> bytes(p)

Accessing individual parts

To access the individual "parts" (components) of a path, use the following property:

Methods and properties

Pure paths provide the following methods and properties:

Concrete paths

Concrete paths are subclasses of the pure path classes. In addition to operations provided by the latter, they also provide methods to do system calls on path objects. There are three ways to instantiate concrete paths:

A subclass of :class:`PurePath`, this class represents concrete paths of the system's path flavour (instantiating it creates either a :class:`PosixPath` or a :class:`WindowsPath`):

>>> Path('')

pathsegments is specified similarly to :class:`PurePath`.

A subclass of :class:`Path` and :class:`PurePosixPath`, this class represents concrete non-Windows filesystem paths:

>>> PosixPath('/etc')

pathsegments is specified similarly to :class:`PurePath`.

A subclass of :class:`Path` and :class:`PureWindowsPath`, this class represents concrete Windows filesystem paths:

>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')

pathsegments is specified similarly to :class:`PurePath`.

You can only instantiate the class flavour that corresponds to your system (allowing system calls on non-compatible path flavours could lead to bugs or failures in your application):

>>> import os
>>> Path('')
>>> PosixPath('')
>>> WindowsPath('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "", line 798, in __new__
    % (cls.__name__,))
NotImplementedError: cannot instantiate 'WindowsPath' on your system


Concrete paths provide the following methods in addition to pure paths methods. Many of these methods can raise an :exc:`OSError` if a system call fails (for example because the path doesn't exist):