🎨 Python’s pathlib
– The Modern Way to Handle Paths
Think of pathlib
as a Swiss Army Knife 🛠️ for handling files and folders.
Instead of old-school string-based paths, it gives you objects that are smart, flexible, and easy to use.
from pathlib import Path
🔑 Here, Path
is the main hero class – it represents a file or folder path.
p = Path("documents/myfile.txt")
👉 Represents a file path object.
💡 Works for both Windows (C:) and Linux (/home/) paths – no worries about slashes /
vs \
.
p.parent # gives folder path
p.name # file name
p.stem # name without extension
p.suffix # extension
🎯 Instead of splitting strings, just ask the object!
new_path = Path("documents") / "images" / "photo.png"
⚡ Cleaner than "documents/images/photo.png"
–
Just use /
like a path magician 🪄
p.exists() # True or False
p.is_file() # is it a file?
p.is_dir() # is it a folder?
✅ No need to import os.path
– it’s all inside!
# Write
p.write_text("Hello, Pathlib!")
# Read
text = p.read_text()
🖋️ Simple file I/O without boilerplate.
for file in Path("documents").iterdir():
print(file)
📜 Loop through everything in a folder easily.
p.resolve() # full absolute path
p.relative_to("documents")
🧭 Helps in navigation and normalization of paths.
pathlib
is Better than os.path
🔹 Object-Oriented 🧑💻
🔹 Cross-platform 🌍
🔹 Cleaner syntax ✨
🔹 Fewer imports 📦
Path Creation → 📂
Join with / → 🛣️
Check file/dir → ✅❌
Read/Write → 🖋️📖
Iterate → 🔄
👉 In short:
pathlib.Path
= Smart, colorful, and platform-independent path handler for Python.