pathlib
The `pathlib` module provides an object-oriented interface for handling filesystem paths, simplifying path manipulations and making code more readable and concise compared to traditional modules like `os.path`. It has been part of Python's standard library since Python 3.4. The PyPI package 'pathlib' (version 1.0.1) is a backport for Python 3.3 and earlier, and Python 2.6/2.7. The module's features evolve with each Python version.
Warnings
- gotcha Avoid converting `Path` objects to strings (`str(path_obj)`) too early, as this loses all the benefits of the `Path` object's methods and object-oriented features. Most modern Python functions and libraries (since Python 3.6, including `open()`, `shutil.copy()`, `json.load`/`json.dump`, `subprocess.run`) natively accept `Path` objects.
- deprecated The `pathlib` PyPI backport (version 1.0.1) is no longer maintained. For Python 2.7, `pathlib2` is the recommended and more actively maintained backport to provide similar functionality to the standard library `pathlib`.
- breaking The semantics of certain methods, like `Path.iterdir()`, can change between major Python versions. For instance, in Python 3.13, `Path.iterdir()` started evaluating a portion of the generator eagerly, potentially raising `FileNotFoundError` earlier if the directory doesn't exist, which was not the case in 3.12 (lazy evaluation).
- gotcha While `pathlib` provides `PurePosixPath` and `PureWindowsPath` for platform-agnostic path manipulation, using them explicitly can lead to `NotImplementedError` if you try to instantiate a platform-specific concrete path (e.g., `WindowsPath` on Unix) directly or if I/O operations are attempted with a `PurePath` object. Use `Path` for platform-appropriate concrete paths unless you specifically need pure path operations without I/O or cross-platform path *representation*.
- gotcha Mixing `pathlib` objects with functions from the `os` or `os.path` modules can negate `pathlib`'s benefits, often requiring unnecessary `str()` conversions. `pathlib` aims to consolidate and replace most `os.path` functionality.
Install
-
# For Python 3.4 and later, pathlib is part of the standard library and does not require installation. -
pip install pathlib -
pip install pathlib2
Imports
- Path
from pathlib import Path
Quickstart
import os
from pathlib import Path
# Create a path object
current_dir = Path.cwd()
example_dir = current_dir / "my_data"
example_file = example_dir / "report.txt"
# Ensure the directory exists
example_dir.mkdir(exist_ok=True)
# Write to a file
example_file.write_text("This is a test report.\n")
print(f"Created file: {example_file.resolve()}")
# Read from a file
content = example_file.read_text()
print(f"File content: {content.strip()}")
# Check properties
print(f"Is it a file? {example_file.is_file()}")
print(f"File name: {example_file.name}")
print(f"File suffix: {example_file.suffix}")
print(f"Parent directory: {example_file.parent.name}")
# Clean up (optional)
example_file.unlink()
example_dir.rmdir()
print("Cleaned up example directory and file.")