Path.py (jaraco/path)

17.1.1 · active · verified Sat Apr 11

The 'path' library provides an object-oriented approach to file system paths, building upon the functionality of `os.path`. Distinct from the built-in `pathlib.Path`, `path.Path` objects are implemented as subclasses of `str`, allowing them to often be passed directly to functions expecting string paths without explicit conversion. It offers a range of convenience methods for common file and directory operations, aiming for a more Pythonic and robust way to interact with the filesystem. The current version is 17.1.1, and the project maintains a fairly active release schedule with several updates per year.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic file system operations using `path.Path` objects, including creating paths, ensuring directories exist, writing to and reading from files, checking existence, globbing, and cleanup. It highlights the use of the `/` operator for joining paths and methods like `makedirs_p()` and `rmdir_p()` for directory management.

from path import Path
import os

# Get current working directory
current_dir = Path.cwd()
print(f"Current directory: {current_dir}")

# Create a new path by joining components
# The '/' operator is overloaded for path concatenation
my_dir = current_dir / "temp_data"
my_file = my_dir / "example.txt"
print(f"Target file path: {my_file}")

# Ensure parent directories exist before creating the file
my_dir.makedirs_p() # Creates parent directories if they don't exist

# Write content to a file
my_file.write_text("Hello, path.py!\nThis is a test file.", encoding='utf-8')

# Read content from a file
content = my_file.read_text(encoding='utf-8')
print(f"Content of {my_file.name}:\n{content}")

# Check if path exists
if my_file.exists():
    print(f"'{my_file.name}' exists.")

# Iterate over files with a pattern (globbing)
print("Python files in current directory:")
for f in current_dir.files("*.py"):
    print(f"- {f.name}")

# Clean up: remove the created file and its parent directory
my_file.remove()
my_dir.rmdir_p() # Removes the directory and its parents if empty

view raw JSON →