Python pathlib Module
Example
Work with paths using objects instead of strings:
from pathlib import Path
p = Path("/home/user") / "projects" / "demo.txt"
print(p.name)
print(p.parent)
print(p.suffix)
Try it Yourself »
Definition and Usage
The pathlib module provides classes that represent filesystem paths as objects.
Use it to build, query, and manipulate paths in a readable, cross-platform way, without manual string handling.
Members
| Member | Description |
|---|---|
| Path | Main path class with methods for common filesystem operations. |
| Path.cwd() | Return the current working directory as a Path. |
| Path.home() | Return the current user’s home directory as a Path. |
| Path.is_dir() | Return True if this path points to an existing directory. |
| Path.is_file() | Return True if this path points to an existing regular file. |
| Path.iterdir() | Iterate over directory contents (children) of this path. |
| Path.read_text() | Read the file’s contents and return a string. |
| Path.resolve() | Resolve symlinks and return an absolute path. |
| Path.write_text() | Write text to the file, creating it if needed. |
| PosixPath | Concrete path implementation for POSIX systems. |
| PurePath | Pure path operations that don’t access the filesystem. |
| PurePosixPath | Pure path for POSIX semantics (no filesystem calls). |
| PureWindowsPath | Pure path for Windows semantics (no filesystem calls). |
| WindowsPath | Concrete path implementation for Windows systems. |