Skip to content
pathlib logo

pathlib

Object-oriented filesystem paths for Python.

SkillDoAI/skilldo0installs2stars

SKILL.md

Full skill instructions

Imports

from pathlib import Path
import os

Core Patterns

Basic Path Creation

Create and manipulate filesystem paths.

from pathlib import Path

# Create a path
p = Path('/​tmp/​example.txt')

# Check if it exists
if p.exists():
    print(f"File exists: {p}")

# Get parts
print(f"Name: {p.name}")
print(f"Parent: {p.parent}")

Reading Files

Read file contents using Path.

from pathlib import Path

p = Path('/​tmp/​example.txt')

# Write
p.write_text('Hello World!')

# Read
content = p.read_text()
print(f"Content: {content}")

Directory Iteration

Iterate over files in a directory.

from pathlib import Path

# List all Python files
for file in Path('.').glob('*.py'):
    print(f"Found: {file.name}")

Configuration

Path objects are immutable and work consistently across platforms.

Pitfalls

Wrong: Using string concatenation for paths

path = '/​tmp' + '/' + 'file.txt'  # Platform-specific

Right: Use Path division operator

from pathlib import Path
path = Path('/​tmp') / 'file.txt'  # Cross-platform

References