Why is `pathlib.Path` generally recommended over `os.path` string manipulation for filesystem paths?
Answer
`os.path` represents a path as a plain string and provides free functions like `os.path.join()` and `os.path.splitext()` that operate on it, which works but scatters path logic across unrelated function calls and requires care about separator differences between operating systems. `pathlib.Path` represents a path as an object with methods and the `/` operator overloaded for joining (`base_dir / "sub" / "file.txt"`), handles Windows-versus-POSIX separators transparently, and bundles related operations like `.exists()`, `.read_text()`, `.glob()` and `.parent` directly onto the object instead of requiring separate module-level function calls.
Strong answer includes
- os.path treats a path as a plain string with free functions operating on it
- pathlib.Path is an object with the / operator overloaded for joining
- handles OS-specific separators transparently, bundles related operations as methods
Practical example
Path("data") / "reports" / f"{year}.csv"builds a correct path on both Windows and Linux without ever writing a literal `/` or `\\` separator.