pathlib

1.0.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates creating a `Path` object, ensuring a directory exists, writing and reading text to/from a file, and accessing common path properties. It concludes with a cleanup of the created directory and file.

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.")

view raw JSON →