Back
+15 XP
Concept

Modern Path Manipulation with `pathlib.Path`

`pathlib.Path` provides cross-platform, object-oriented filesystem paths. Join paths intuitively using the division operator: `dir / "sub" / "file.txt"`.

python
from pathlib import Path

p = Path("home") / "user" / "config.json"
print(p.name)    # config.json
print(p.suffix)  # .json
print(p.parent)  # home/user

# 14. Modern Path Manipulation with `pathlib.Path` `pathlib.Path` provides cross-platform, object-oriented filesystem paths. Join paths intuitively using the division operator: `dir / "sub" / "file.txt"`: ```python from pathlib import Path p = Path("home") / "user" / "config.json" print(p.name) # config.json print(p.suffix) # .json print(p.parent) # home/user ``` Forget brittle legacy string concatenations with `os.path.join()`. `pathlib` automatically uses backslashes on Windows and forward slashes on Linux/macOS, eliminating cross-platform path bugs.

Checkpoint

Which operator does `pathlib.Path` overload for joining subdirectories and filenames?

Practice

Use `Path("data/reports/annual.csv")` to print its file extension with `.suffix`.

Terminal
01
Tap code blocks below to assemble
Available Blocks