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"))- Expected output: sales.csv sales reports/sales.json
- 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