0Pricing
AI Agents · Lesson

Safe File Operations with Error Handling

Checking file existence, permissions, and handling IO errors gracefully.

Why Safe File Operations Matter

File operations in agents can fail in many ways: the file doesn't exist, the agent lacks permission, the path is a directory, or disk space runs out mid-write. An agent that crashes on a file error leaves partial output and corrupted state. Defensive programming with proper checks and error handling makes agents resilient.

from pathlib import Path

# Unsafe: crashes with FileNotFoundError
# content = Path('missing.txt').read_text()

# Safe: check first
path = Path('config.json')
if path.exists():
    content = path.read_text(encoding='utf-8')
    print('Loaded config')
else:
    print(f'Config not found at {path.resolve()}')
    content = '{}'  # use default

Path.exists() and Path.is_file()

Before reading a file, check that it exists and is actually a regular file (not a directory, symlink to a directory, or special file). Path.exists() returns True for any filesystem object; Path.is_file() returns True only for regular files.

from pathlib import Path

path = Path('data/report.csv')

# Chain of checks
if not path.exists():
    print(f'Not found: {path}')
elif not path.is_file():
    print(f'Not a regular file: {path} (is_dir={path.is_dir()})')
elif path.stat().st_size == 0:
    print(f'File is empty: {path}')
else:
    # Safe to read
    import csv
    with open(path, 'r', encoding='utf-8', newline='') as f:
        reader = csv.DictReader(f)
        rows = list(reader)
    print(f'Read {len(rows)} rows')

All lessons in this course

  1. Reading and Writing Files in Agent Context
  2. Directory Traversal and File Discovery
  3. File Format Handling: CSV, JSON, and TXT
  4. Safe File Operations with Error Handling
← Back to AI Agents