pathlib2 Library

2.3.7.post1 · maintenance · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates basic usage of `pathlib2.Path` to represent filesystem paths, check existence, manipulate path components, and create/delete files and directories.

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()

view raw JSON →