0PricingLogin
AI Agents · Lesson

File Format Handling: CSV, JSON, and TXT

csv module, json.load/dump, and safe text encoding for agent tools.

The Three Most Common Agent File Formats

Agents read and write three file formats constantly: CSV for tabular data, JSON for structured objects, and plain text for logs, prompts, and reports. Each has different parsing requirements, edge cases, and best practices. Python has excellent built-in support for all three.

import csv
import json
from pathlib import Path

# Detect format from extension
def read_data_file(file_path):
    path = Path(file_path)
    if path.suffix == '.csv':
        return read_csv(path)
    elif path.suffix == '.json':
        return read_json(path)
    elif path.suffix == '.txt':
        return path.read_text(encoding='utf-8')
    else:
        raise ValueError(f'Unsupported format: {path.suffix}')

csv.reader — Basic CSV Parsing

csv.reader parses a CSV file row by row, returning each row as a list of strings. It handles quoted fields, embedded commas, and newlines inside quoted values correctly — unlike splitting on commas manually, which breaks on edge cases.

import csv

# Basic reading with csv.reader
with open('sales.csv', 'r', encoding='utf-8', newline='') as f:
    reader = csv.reader(f)
    header = next(reader)  # read the header row
    print('Columns:', header)

    for row in reader:
        # row is a list of strings
        product = row[0]
        quantity = int(row[1])
        price = float(row[2])
        print(f'{product}: {quantity} units at ${price}')

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