Course OverviewFree AI CourseBlogReserve Bootcamp Seat
Python for AI · Day 3 of 5 ~75 minutes

Working with Files and APIs

Read files, call the Claude API for the first time, handle errors gracefully, and save results to CSV. This is the day everything becomes real.

1
Day 1
2
Day 2
3
Day 3
4
Day 4
5
Day 5
What You'll Build Today

A Python script that reads a list of questions from a text file, sends each one to Claude's API, and saves all the responses to a CSV file — ready for review or analysis.

1
File I/O

Reading and Writing Files

Python uses the with open() pattern for file operations. The with block automatically closes the file when done, even if an error occurs.

pythonfile_io.py
import csv

# Read a text file
with open("questions.txt", "r") as f:
    questions = f.readlines()  # list of lines

# Strip whitespace/newlines
questions = [q.strip() for q in questions if q.strip()]

# Write a text file
with open("output.txt", "w") as f:
    f.write("Processing complete\n")
    f.write(f"Processed {len(questions)} questions\n")

# Read a CSV
with open("data.csv", "r") as f:
    reader = csv.DictReader(f)
    rows = list(reader)  # list of dicts, one per row

# Write a CSV
results = [
    {"question": "What is AI?", "answer": "...", "tokens": 142}
]
with open("results.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["question", "answer", "tokens"])
    writer.writeheader()
    writer.writerows(results)
2
The Claude API

Your First Real API Call

First, install the Anthropic SDK and get your API key.

bash
$ pip install anthropic

Go to console.anthropic.com, create an account, and generate an API key. Store it as an environment variable — never hardcode it in your script.

bashset your API key
# Mac/Linux
$ export ANTHROPIC_API_KEY="sk-ant-..."

# Windows PowerShell
> $env:ANTHROPIC_API_KEY="sk-ant-..."

Now make your first API call:

pythonfirst_call.py
import anthropic

client = anthropic.Anthropic()
# Reads ANTHROPIC_API_KEY from environment automatically

message = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain what a CSV file is in one sentence."}
    ]
)

# Extract the text response
response_text = message.content[0].text
print(response_text)

# Check token usage
print(f"Input: {message.usage.input_tokens} tokens")
print(f"Output: {message.usage.output_tokens} tokens")

Run this now. If you get a response back, you've just made your first real AI API call. This exact pattern is what every AI application on earth uses.

3
Error Handling

try/except: Handling Errors Gracefully

APIs fail. Networks time out. Files don't exist. try/except lets your program handle these situations without crashing.

pythonerror_handling.py
import anthropic

client = anthropic.Anthropic()

def ask_claude(question):
    """Ask Claude a question, return text or error message."""
    try:
        message = client.messages.create(
            model="claude-opus-4-5",
            max_tokens=512,
            messages=[{"role": "user", "content": question}]
        )
        return message.content[0].text
    except anthropic.APIConnectionError:
        return "ERROR: Could not connect to API"
    except anthropic.RateLimitError:
        return "ERROR: Rate limit hit — slow down"
    except anthropic.APIStatusError as e:
        return f"ERROR: {e.status_code} — {e.message}"
    except Exception as e:
        return f"Unexpected error: {e}"
Today's Exercise

API + File + CSV Pipeline

Create questions.txt with 3–5 questions (one per line). Then build a script that reads them, sends each to Claude, and saves the results to results.csv.

  • Read questions from questions.txt using with open()
  • Loop through questions, call ask_claude() for each
  • Build a list of dicts: {"question": ..., "answer": ..., "tokens": ...}
  • Write the list to results.csv using csv.DictWriter
  • Wrap everything in try/except so errors don't crash the whole run

What You Learned Today

  • Reading text files and CSVs with with open()
  • Writing CSVs with csv.DictWriter
  • Installing libraries with pip and managing API keys as environment variables
  • Making your first Claude API call and extracting the response text
  • Handling API errors gracefully with try/except
Course Progress
Day 3 of 5 — 60%
Day 3 Complete

Day 4: Data Analysis with Pandas

Tomorrow you'll load that CSV you just created into pandas and pull real insights from it.

Start Day 4