Platform-aware path construction
Constructing portable filesystem locations in backend or scripting code.
Python · Module
pathlib supplies object-oriented filesystem path classes. Use Path for platform-aware filesystem operations and pure path classes for calculations that do not access the filesystem.
Use pathlib.Path for object-oriented filesystem paths. Pure path classes calculate path information without filesystem access, while concrete paths also perform filesystem operations; Path selects the concrete path appropriate for the running platform.
class pathlib.Path(*pathsegments)| Name | Type | Description |
|---|---|---|
*pathsegments | str or os.PathLike | Path segments or path-like values used to construct the path object. |
A path object representing the supplied filesystem path.
from pathlib import Path
root = Path(".")
for path in root.glob("*.py"):
print(path.name)Creates a platform-aware path and prints the names of Python files in the current directory.
Constructing portable filesystem locations in backend or scripting code.
Combining, inspecting, or transforming path values without filesystem I/O.
Finding files and performing filesystem operations through concrete paths.
pathlib represents filesystem paths with objects rather than relying only on path strings. Pure paths perform computational path operations without I/O, while concrete paths also provide system calls.
Follow-up: When should you use PurePath instead of Path? Use PurePath when you need path manipulation without accessing the filesystem, such as analyzing a path for another operating system.
Path is the main concrete class to use when the appropriate platform-specific path is desired. It instantiates a concrete path for the platform where the program runs.
Follow-up: How can code remain portable across operating systems? Construct paths through Path and its methods rather than embedding platform-specific separators.
Pure paths are limited to path-handling calculations, whereas concrete paths inherit those operations and add filesystem system calls. This separation lets code manipulate paths without triggering I/O.
Follow-up: Why is this separation useful in testing? Pure path logic can be tested without creating, reading, or inspecting filesystem entries.
PurePathPurePosixPathPureWindowsPathPathPosixPathWindowsPath