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.
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.
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)
Your First Real API Call
First, install the Anthropic SDK and get your API key.
$ 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.
# Mac/Linux
$ export ANTHROPIC_API_KEY="sk-ant-..."
# Windows PowerShell
> $env:ANTHROPIC_API_KEY="sk-ant-..."
Now make your first API call:
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.
try/except: Handling Errors Gracefully
APIs fail. Networks time out. Files don't exist. try/except lets your program handle these situations without crashing.
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}"
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.txtusingwith open() - Loop through questions, call
ask_claude()for each - Build a list of dicts:
{"question": ..., "answer": ..., "tokens": ...} - Write the list to
results.csvusingcsv.DictWriter - Wrap everything in
try/exceptso 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
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