Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Standard library & toolingJuniorCommonPractical

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

Python example
Path("data") / "reports" / f"{year}.csv"

builds a correct path on both Windows and Linux without ever writing a literal `/` or `\\` separator.

#pathlib#filesystem

Sources

pathlib — Object-oriented filesystem pathsPython Software Foundation · Cross-platform path handling that replaces most os.path usageTop Python Interview Questions and AnswersDataCamp · Coverage signal for data-oriented and standard-library questions