SyntaxStudy
Sign Up
Python Intermediate 9 min read

pathlib & os.path

pathlib & os.path

pathlib (Python 3.4+) provides an object-oriented API for file system paths. It is the modern alternative to the string-based os.path module.

Creating Path Objects

from pathlib import Path

p = Path("/home/user/documents/report.pdf")
cwd = Path.cwd()
home = Path.home()

Path Properties

p = Path("/home/user/data/report.csv")
print(p.name)       # report.csv
print(p.stem)       # report
print(p.suffix)     # .csv
print(p.parent)     # /home/user/data
print(p.parts)      # ('/', 'home', 'user', 'data', 'report.csv')

Building Paths

base = Path("/projects")
full = base / "myapp" / "config" / "settings.json"
print(full)

Checking & Operations

p = Path("data.txt")
print(p.exists())
print(p.is_file())
print(p.is_dir())

p.touch()           # create file
p.write_text("hello", encoding="utf-8")
print(p.read_text(encoding="utf-8"))
p.unlink()          # delete file

Globbing & Iterating

d = Path("/home/user")
for f in d.glob("*.txt"):
    print(f)
for f in d.rglob("*.py"):   # recursive
    print(f)

os.path Equivalents

import os
print(os.path.join("/home", "user", "file.txt"))
print(os.path.exists("/home/user"))
print(os.path.basename("/home/user/file.txt"))  # file.txt
print(os.path.splitext("report.csv"))  # ('report', '.csv')
Example
from pathlib import Path

p = Path("sample.txt")
p.write_text("Line 1
Line 2
Line 3", encoding="utf-8")
print("Exists:", p.exists())
print("Size:", p.stat().st_size, "bytes")
print("Stem:", p.stem)
print("Suffix:", p.suffix)
content = p.read_text(encoding="utf-8")
print("Lines:", len(content.splitlines()))
p.unlink()
Pro Tip

Prefer pathlib over os.path for new code. The / operator for path joining is clean, readable, and cross-platform.