Sponsored Reserved space — layout preview until AdSense is connected

Python

pathlib — the modern way to handle file paths in Python

Build, join, and inspect paths with objects instead of brittle string concatenation and os.path calls.

May 2026 · 7 min read · 2 views · 0 hearts

pathlib.Path replaces most of os.path with an object-oriented API that works the same on Windows, macOS, and Linux.

Joining paths with /

The slash operator joins path parts safely — no manual separators:

from pathlib import Path

config = Path.home() / ".config" / "app.toml"
print(config.exists())

Reading and writing

Small files become one-liners, with encoding handled explicitly:

data = Path("notes.txt").read_text(encoding="utf-8")
Path("out.txt").write_text(data.upper(), encoding="utf-8")

Useful properties

  • .name, .stem, and .suffix split a filename for you.
  • .parent walks up the tree.
  • .glob("*.py") lists matching files without extra imports.

Once you switch, string-based path code starts to feel error-prone by comparison.

Comments

Questions, corrections, and tips stay visible for everyone reading this page.

0 in thread

Join the discussion

Shown next to your comment.

Constructive tone · up to 4,000 characters

No comments yet

Be the first to leave a note — it helps the next reader.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected