pathlib.Path
Path is PurePath plus I/O. Build it from strings, join with /, then ask it questions (exists, is_file) or act on it (read_text, mkdir, glob). Relative paths are resolved against the current working directory at the moment you use them.
Demo
from pathlib import Path (Path('data') / 'raw/sales.csv').as_posix()
The join tab shows as_posix() so the result reads the same on every OS; str() would show backslashes on Windows. "data/" and "data" join identically because the trailing slash is dropped when the path is parsed, and an absolute child like "/etc/hosts" discards the base completely.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| *pathsegments | str | os.PathLike | no ('.') | Joined like os.path.join. Path() with no arguments is the current directory, ".". |
Return value
PosixPath | WindowsPath — Path itself is a factory: you get the concrete class for the running OS.
Common patterns
from pathlib import Path DATA = Path(__file__).resolve().parent / 'data'
from pathlib import Path def word_count(path): return len(Path(path).read_text(encoding='utf-8').split())
import shutil from pathlib import Path src = Path('report.pdf') shutil.copy(src, Path('backup') / src.name)
from pathlib import Path home = Path.home() here = Path.cwd()
Examples
Pitfalls
import os from pathlib import Path str(Path('a') / 'b') == ('a\\b' if os.name == 'nt' else 'a/b')
from pathlib import Path (Path('a') / 'b').as_posix()
from pathlib import PurePosixPath PurePosixPath('report') + '.pdf'
from pathlib import PurePosixPath PurePosixPath('report').with_suffix('.pdf')
import os from pathlib import PosixPath, WindowsPath foreign = PosixPath if os.name == 'nt' else WindowsPath try: foreign('x') except Exception as e: result = type(e).__name__ result
from pathlib import PurePosixPath, PureWindowsPath (PurePosixPath('x'), PureWindowsPath('x'))
When to use
- Every file-system path in new code
- Small whole-file reads and writes (read_text / write_bytes …)
- Listing and searching directories (iterdir, glob, rglob, walk)
- Paths that are not on this machine → PurePosixPath / PureWindowsPath
- Recursive copy / delete → shutil.copytree / shutil.rmtree
Notes
FAQ
PurePath only works with the path text; Path adds methods that touch the file system (exists, read_text, mkdir, glob, stat …). Path is a subclass of PurePath, so it also has every pure method.