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.
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
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
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 →