Source

pathlib / docs / index.rst

pathlib

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. If using it with Python 3.3, you also have access to optional openat-based filesystem operations.

Download

Releases are available on PyPI: http://pypi.python.org/pypi/pathlib/

The development repository and issue tracker can be found at BitBucket: https://bitbucket.org/pitrou/pathlib/

Basic use

Importing the module classes:

>>> from pathlib import *

Listing subdirectories:

>>> p = Path('.')
>>> [x for x in p 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('test_pathlib.py'), PosixPath('setup.py'),
 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
 PosixPath('build/lib/pathlib.py')]

Navigating inside a directory tree:

>>> p = Path('/etc')
>>> q = p['init.d/reboot']
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

Querying path properties:

>>> q.exists()
True
>>> q.is_dir()
False
>>> q.st_mode
33261

Opening a file:

>>> with q.open() as f: f.readline()
...
'#!/bin/bash\n'

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 subclass of :class:`PurePath`, this path flavour represents non-Windows filesystem paths:

>>> PurePosixPath('/etc')
PurePosixPath('/etc')

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

>>> PureNTPath('c:/Program Files/')
PureNTPath('c:\\Program Files')

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

>>> PurePath('setup.py')
PurePosixPath('setup.py')

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.

Constructing paths

Path constructors accept an arbitrary number of positional arguments. When called without any argument, a path object points to the current directory:

>>> PurePath()
PurePosixPath('.')

Any argument can be a string or bytes object representing an arbitrary number of path segments, but it can also be another path object:

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

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

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

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

>>> PureNTPath('c:/Windows', '/Program Files')
PureNTPath('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')
PurePosixPath('foo/bar')
>>> PurePath('foo/./bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/../bar')
PurePosixPath('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)

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')
False
>>> PureNTPath('foo') == PureNTPath('FOO')
True
>>> PureNTPath('FOO') in { PureNTPath('foo') }
True
>>> PureNTPath('C:') < PureNTPath('d:')
True

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

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

Operators

Indexing a path helps create child paths, similarly to os.path.join:

>>> p = PurePath('/etc')
>>> p
PurePosixPath('/etc')
>>> p['passwd']
PurePosixPath('/etc/passwd')
>>> p['init.d/apache2']
PurePosixPath('/etc/init.d/apache2')

The string representation of a path is the raw filesystem path itself, which you can pass to any function taking a file path as a string:

>>> p = PurePath('/etc')
>>> str(p)
'/etc'

Similarly, calling bytes on a path gives the raw filesystem path as a bytes object:

>>> bytes(p)
b'/etc'

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 an 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:`Path` and :class:`PurePosixPath`, this class represents concrete non-Windows filesystem paths:

>>> PosixPath('/etc')
PosixPath('/etc')

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

>>> NTPath('c:/Program Files/')
NTPath('c:\\Program Files')

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:`NTPath`):

>>> Path('setup.py')
PosixPath('setup.py')

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
>>> os.name
'posix'
>>> Path('setup.py')
PosixPath('setup.py')
>>> PosixPath('setup.py')
PosixPath('setup.py')
>>> NTPath('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 798, in __new__
    % (cls.__name__,))
NotImplementedError: cannot instantiate 'NTPath' on your system

Iterating

When a concrete path points to a directory, iterating over it yields path objects of the directory contents:

>>> p = Path('docs')
>>> for child in p: child
...
PosixPath('docs/conf.py')
PosixPath('docs/_templates')
PosixPath('docs/make.bat')
PosixPath('docs/index.rst')
PosixPath('docs/_build')
PosixPath('docs/_static')
PosixPath('docs/Makefile')

Methods

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):

Attributes

Concrete paths provide the following attributes: