Skip to content
Justice Tech School

pathlib for File Paths

pathlib.Path represents paths as objects. Use / to join, exists, read_text, write_text and glob.

Example
from pathlib import Path
import tempfile
d = Path(tempfile.mkdtemp())
f = d / "a.txt"
f.write_text("hi")
print(f.name, f.suffix, f.read_text(), f.exists())
f.unlink(); d.rmdir()

Result

a.txt .txt hi True

Exercise

Join paths.

Path("a")  "b"

Quiz Test

What does Path("x.txt").suffix give?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.