Codectionary / Developer documentation / Python

Pathlib and Portable Paths

Path objects join and inspect filesystem paths without manual separator concatenation. PurePath variants perform only lexical operations; concrete Path objects can also access files. Run as a Python 3.11+ script.

Syntax

Path(directory) / filename; path.name; path.with_suffix(".json")

Examples

Pathlib and Portable Paths

Run as a Python 3.11+ script.

from pathlib import PurePosixPath
path = PurePosixPath("reports") / "sales.csv"
print(path.name)
print(path.stem)
print(path.with_suffix(".json"))
  1. Expected output: sales.csv sales reports/sales.json
  2. PurePosixPath makes this demonstration identical on Windows and Unix. with_suffix returns a new path; it does not rename a file.

Best practices

  • Use Path for local filesystem operations and an explicit pure-path flavor to interpret paths from another OS.
  • Joining a path does not create a directory or ensure the target exists.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading