Table of Contents

import pathlib

import pathlib is a Python import that provides object-oriented filesystem paths. Prefer pathlib.Path over os.path for modern code; it's more readable and handles cross-platform paths automatically.

Example

# Python
# description: create paths, check existence, read files
 
from pathlib import Path
 
# Create a path object
p = Path("data/config.txt")
 
# Check if file exists
if p.exists():
    print(f"File exists at {p.resolve()}")
 
# Get file properties
print(f"Size: {p.stat().st_size} bytes")
 
# Read file contents
content = p.read_text()
 
# Write to file
output = Path("output.txt")
output.write_text("Hello, World!")
 
# Iterate over files in directory
for file in Path(".").glob("*.py"):
    print(file.name)

Common methods