Python Pathlib

pathlib is a module providing a consistent and powerful interface for path-like objects. The pathlib.Path object should be acceptable wherever a path-like object can be used.


Usage

The core functionality of the pathlib module is the pathlib.Path class.

Example

from pathlib import Path

# instantiate a relative path
p = Path('.')      # '.'

# append to the path
p.joinpath('temp') # './temp'

# replace the extension of a file
old = Path('archive.tar.gz')
new = old.with_suffix('.txt')  # 'archive.txt'

Methods

Method

Meaning

absolute()

anchor()

as_posix()

as_uri()

chmod()

drive()

exists()

test if the file/directory represented by the path exists

expanduser()

glob()

group()

hardlink_to()

is_absolute()

test if the path is absolute

is_block_device()

is_char_device()

is_dir()

is_fifo()

is_file()

is_mount()

is_relative_to()

test if the path is relative to another path

is_reserved()

on Windows only, test if the path is reserved

is_socket()

is_symlink()

iterdir()

joinpath()

append path-like objects

match()

test if the path matches a glob pattern

mkdir()

create the directory represented by the path; can raise FileNotFoundError or FileExistsError

name()

open()

owner()

parent()

parents()

parts()

read_bytes()

read_text()

readlink()

relative_to()

return a new pathlib.Path object representing the path relative to another path

rename()

replace()

resolve()

rglob()

rmdir()

root()

samefile()

stat()

return a os.stat_result for the file represented by the path

stem()

suffix()

suffixes()

symlink_to()

touch()

unlink()

with_name()

return a new pathlib.Path object representing the path with the final component replaced with another filename

with_stem()

return a new pathlib.Path object representing the path with the final component's basename replaced with another basename

with_segments()

with_suffix()

return a new pathlib.Path object representing the path with the final component's extension replaced with another extension

write_bytes()

write_text()

Class Methods

There are also two class methods for instantiating commonly-used paths.

Method

Value

Path.cwd()

current working directory

Path.home()

home directory


Classes

Apart from pathlib.Path, there are several classes exposed for alternative and niche functionality.

Class

Meaning

pathlib.PosixPath

POSIX-only class

pathlib.PurePath

base class that does not interact with the actual filesystem

pathlib.PurePosixPath

base POSIX class that does not interact with the actual filesystem

pathlib.PureWindowsPath

base Windows class that does not interact with the actual filesystem

pathlib.WindowsPath

Windows-only class


See also

Python pathlib module documentation

Python Module of the Day article for pathlib


CategoryRicottone

Python/PathLib (last edited 2023-10-11 19:40:58 by DominicRicottone)