pathlib Module
The pathlib module, introduced in Python 3.4 and made the recommended approach in Python 3.6 and later, provides an object-oriented interface for working w...
Modern Path Handling with Python pathlib
The pathlib module, introduced in Python 3.4 and made the recommended approach in Python 3.6 and later, provides an object-oriented interface for working with filesystem paths. Instead of treating paths as plain strings and calling functions from os.path, you work with Path objects that have methods and properties built in.
from pathlib import Path
p = Path("/home/user/documents") print(p.exists()) # True or False print(p.is_dir()) # True if it is a directory print(p.name) # "documents" print(p.parent) # /home/user print(p.suffix) # "" (no file extension here)
file_path = Path("/home/user/notes.txt") print(file_path.stem) # "notes" print(file_path.suffix) # ".txt"
The forward slash operator / is overloaded on Path objects to join path components. This is much cleaner than os.path.join() and reads like an actual path:
base = Path("/home/user") config = base / "config" / "settings.json" print(config) # /home/user/config/settings.json
Reading and writing files is also possible directly through Path objects, without calling open() separately:
p = Path("output.txt") p.write_text("Hello from pathlib!\n", encoding="utf-8") content = p.read_text(encoding="utf-8") print(content)
The glob() method lets you search for files matching a pattern. The rglob() method does the same recursively through subdirectories:
src = Path("/home/user/project") for py_file in src.rglob("*.py"): print(py_file)
Creating directories is clean and readable. The mkdir() method with parents=True and exist_ok=True handles the full path and avoids errors if directories already exist:
new_dir = Path("/home/user/new_project/src") new_dir.mkdir(parents=True, exist_ok=True)
You can convert a Path object to a string with str(p) whenever a function requires a plain string path.
Exam tip: Know the difference between Path.resolve(), which returns the absolute path with symlinks resolved, and Path.absolute(), which returns the absolute path without resolving symlinks. Also remember that pathlib paths are immutable; operations like / return new Path objects rather than modifying the original.