Py Pathlib — Free Python Tutorial

Learn Py Pathlib in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Py Pathlib — Free Python Tutorial

Learn Py Pathlib in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

✓ 100% Free ✓ No Login Needed ✓ NCERT / CBSE Aligned ✓ Download as PDF

TL;DR: Learn Py Pathlib in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated

🤖 Stuck on any question? Ask Syllab's free AI Tutor for a step-by-step explanation — instant, unlimited, no login.

Py Pathlib in Python

pathlib (Python 3.4+) provides Path objects for working with file system paths — an object-oriented alternative to string-based os.path manipulation. Paths are represented as objects with methods and properties, not raw strings.

Cross-platform: Path automatically uses / on Unix and \ on Windows so the same code works everywhere. Use forward slash / as the join operator: base / "subdir" / "file.txt".

Key properties: path.name (filename), path.stem (filename without extension), path.suffix (extension like ".py"), path.parent (directory), path.parts (tuple of components).

Key methods: path.exists(), path.is_file(), path.is_dir(), path.mkdir(parents=True), path.read_text(), path.write_text(), path.glob("*.py"), path.rglob("*.py") (recursive).

Py Pathlib — Syntax

from pathlib import Path

p = Path("/home/user/docs/report.pdf")
p.name        # "report.pdf"
p.stem        # "report"
p.suffix      # ".pdf"
p.parent      # Path("/home/user/docs")
p.exists()    # True/False

# Join paths with /
new = p.parent / "archive" / "report_v2.pdf"

# Read/write
p.read_text(encoding="utf-8")
p.write_text("content", encoding="utf-8")

Learn Py Pathlib step by step with Syllab's free interactive Python tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Python course →