Construct Paths with pathlib
Core idea
Path represents paths using the host system rules. Join components with /, inspect name, suffix and parent, and use filesystem methods such as is_file. PurePath variants inspect path syntax without accessing files.
from pathlib import Pathp = Path("reports") / "daily.csv"print(p.name, p.suffix, p.parent.name)The components are independent of separator rendering.
Create a child directory
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "reports" / "daily.txt" p.parent.mkdir(parents=True, exist_ok=True) p.write_text("ready", encoding="utf-8") print(p.is_file(), p.parent.is_dir())Constructing a path does not create it; mkdir and write_text do.
Common mistake
Joining an absolute path can discard the earlier base. Do not treat joining an untrusted path to a root as a containment check.
Practice
Build a relative path for a report, inspect its stem and suffix, then create it inside a temporary root.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Path components
Check your understanding of pathlib paths.
What is printed?
from pathlib import Pathprint((Path("a") / "b.tar.gz").suffix)What is printed?
from pathlib import PurePosixPathprint(PurePosixPath("/a") / "/b")Which method creates parent directories?
Does Path("new.txt") create a file?