pathlib.Path

An object-oriented representation of a filesystem path, and the standard, cross-platform way to build and manipulate paths.

                Path(*segments)
              

Purpose

Path represents a filesystem path as an object with methods, replacing manual string concatenation (directory + "/" + filename) with something that works correctly on both Windows (\) and POSIX (/) path separators.

Example

from pathlib import Path

directory = Path("data")
config_path = directory / "config.json"        # Path('data/config.json')

config_path.write_text('{"ready": true}', encoding="utf-8")
text = config_path.read_text(encoding="utf-8")

print(config_path.name)    # "config.json"
print(config_path.suffix)  # ".json"
print(config_path.parent)  # Path('data')

Behavior notes

  • The / operator joins path segments (directory / "config.json") β€” this is Path’s own operator overload, not filesystem division, and it produces the correct separator for whichever platform the code runs on.
  • read_text()/write_text() (and their binary counterparts read_bytes()/write_bytes()) open the file, do the operation, and close it again, all in one call β€” no explicit with block needed for this common case, though a context manager is still what happens internally.
  • Path objects are immutable β€” / and methods like .with_suffix(...) return a new Path rather than modifying the original, the same immutability shape str has.
  • Always pass encoding="utf-8" explicitly for text methods rather than relying on the platform default encoding, which differs between operating systems and can silently produce different bytes for the same text.

Common mistakes

  • Building paths with string concatenation or manual / characters ("data/" + filename) instead of Path β€” this breaks on Windows, where the native separator is \, and doesn’t normalize redundant separators or .. segments the way Path does.
  • Omitting encoding="utf-8" and relying on the platform default β€” code that β€œworks” during development can produce garbled output (or crash on genuinely non-ASCII text) once it runs somewhere with a different default encoding.

Implementation notes

Path’s cross-platform behavior β€” producing the correct separator and semantics for the running operating system β€” is a documented, language-guaranteed feature of the standard library, not a CPython-specific detail.

Taught in these lessons

Related reference