pathlib2 Library
pathlib2 is a backport of the standard library module `pathlib` to Python versions 2.6, 2.7, 3.2, and 3.3. It provides an object-oriented filesystem path abstraction. For Python 3.4 and up, `pathlib` is part of the standard library, making `pathlib2` generally unnecessary for modern projects. The current version is 2.3.7.post1, and it's in community maintenance.
Warnings
- breaking For Python 3.4 and newer, use the standard library module `pathlib` instead of `pathlib2`. `pathlib2` is a backport for older Python versions only.
- gotcha `pathlib2`'s API reflects an older state of the standard library `pathlib`. It does not include features, methods, or bug fixes introduced in `pathlib` in more recent Python versions (e.g., Python 3.5+).
- gotcha The `pathlib2` project is maintained by Jazzband, which implies community maintenance for its intended purpose (older Python versions). Active feature development or significant updates to align with the latest `pathlib` API are not expected.
Install
-
pip install pathlib2
Imports
- Path
from pathlib2 import Path
Quickstart
from pathlib2 import Path
# Create a Path object
p = Path('/tmp/my_file.txt')
# Check if it exists
print(f"Does {p} exist? {p.exists()}")
# Get parent directory
print(f"Parent directory: {p.parent}")
# Get file name
print(f"File name: {p.name}")
# Create a new path by joining
new_dir = Path('/tmp/my_data')
new_dir.mkdir(exist_ok=True)
new_file = new_dir / 'output.log'
new_file.touch()
print(f"New file created: {new_file.exists()}")
print(f"Contents of new_file: {new_file.read_text()}")
# Clean up
new_file.unlink()
new_dir.rmdir()