On this page
  1. pathlib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safe Directory Creation, Atomic-Style Read/Write & Globbing
  7. 2. Pure Path Manipulation Without Touching Disk
  8. Gotchas & Boundaries
  9. Classes & Objects

pathlib

Prev: os | Up: stdlib_module | Next: pdb
Rel: os, io, time, fileinput, stat
Ref: docs.python.org — pathlib
Tags: #public #python3 #stdlib


Import

import pathlib

Overview

Object-oriented filesystem paths that replace string manipulation (os.path.join, os.path.dirname) with composable Path objects. Reach for pathlib.Path for virtually all path construction, traversal, globbing, and small file I/O; drop down to os only for low-level file descriptors, process environment variables, or OS-specific syscalls.

Quick Start

from pathlib import Path

base = Path(__file__).resolve().parent
config = base / "config" / "settings.json"

assert config.name == "settings.json"
assert config.stem == "settings"
assert config.suffix == ".json"
assert config.parent.name == "config"

Implementation Walkthrough

1. Safe Directory Creation, Atomic-Style Read/Write & Globbing

from pathlib import Path

workspace = Path("/tmp/demo_pathlib")
workspace.mkdir(parents=True, exist_ok=True)

notes = workspace / "notes.txt"
notes.write_text("hello world\n", encoding="utf-8")
assert notes.read_text(encoding="utf-8") == "hello world\n"

# Recursive search for all Markdown files under workspace
md_files = sorted(workspace.rglob("*.md"))

2. Pure Path Manipulation Without Touching Disk

Use PurePosixPath or PureWindowsPath when manipulating paths for another OS (such as URLs, container paths, or cross-platform manifests) without performing filesystem syscalls:

from pathlib import PurePosixPath

asset = PurePosixPath("/srv/app/static/logo.png")
assert asset.with_suffix(".webp") == PurePosixPath("/srv/app/static/logo.webp")
assert asset.relative_to("/srv/app") == PurePosixPath("static/logo.png")

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes