Files, text and JSON
AI work is full of text and JSON. This module shows you how to read, write, clean and safely parse them.
Learning objectives
- Read and write text files with encoding
- Convert between JSON and Python with json.loads and json.dumps
- Handle bad input with try/except
- Clean and search text with string methods and regular expressions
- Read and write CSV files
- Navigate nested JSON step by step
- Build a prompt from a list of records
- Read and write JSON Lines
3.1 Reading and writing text files
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("First line\nSecond line\n")
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())
The with block closes the file automatically. Always set encoding="utf-8" for text that might include accents or emojis. (Files you create in these cells live in your browser's memory and disappear when you reload the page.)
3.2 JSON: the language of AI APIs
AI model APIs send requests and responses as JSON. Python's json module converts between JSON text and dictionaries and lists.
import json
raw = '{"category": "DELIVERY", "urgent": true, "summary": "Parcel late"}'
data = json.loads(raw) # JSON text -> Python dict
print(data["category"], data["urgent"]) # DELIVERY True
reply = {"order": "GFY-10422", "items": ["board", "oil"], "total": 31.50}
text = json.dumps(reply, indent=2) # Python -> JSON text
print(text)
with open("reply.json", "w") as f:
f.write(text)
Note how JSON true becomes Python True, and null becomes None.
3.3 Handling bad data with try/except
AI models sometimes return text that isn't valid JSON. Handle it rather than crashing:
def parse_json(text):
try:
return json.loads(text)
except json.JSONDecodeError:
return None
print(parse_json('{"ok": true}')) # {'ok': True}
print(parse_json("Sure! Here is JSON:")) # None
3.4 Cleaning text
import re
def clean(text):
text = text.strip().lower()
text = re.sub(r"\s+", " ", text) # collapse repeated spaces/newlines
text = re.sub(r"[^\w\s£.,!?'-]", "", text) # drop unusual symbols
return text
print(clean(" GREAT board!!! 😀\n\nArrived late "))
re is Python's regular expressions module — handy for finding patterns such as order numbers or email addresses.
3.5 CSV files
import csv
rows = [{"id": 1, "text": "Love it", "stars": 5}, {"id": 2, "text": "Too small", "stars": 2}]
with open("reviews.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["id", "text", "stars"])
writer.writeheader()
writer.writerows(rows)
with open("reviews.csv", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["text"], row["stars"])
For anything beyond simple CSVs, you'll use pandas (Module 4).
3.6 Reading nested JSON
Real API responses are dictionaries inside lists inside dictionaries. The skill is following the path to the piece you want, one step at a time.
import json
raw = """{
"model": "example-model",
"content": [{"type": "text", "text": "Your order has been dispatched."}],
"usage": {"input_tokens": 42, "output_tokens": 9},
"stop_reason": "end_turn"
}"""
response = json.loads(raw)
print(list(response.keys())) # what is at the top level?
print(response["usage"]["output_tokens"]) # a dictionary inside a dictionary
print(response["content"][0]["text"]) # a dictionary inside a list inside a dictionary
# A path that might not exist: use .get() with a default at each step
print(response.get("error", {}).get("message", "no error"))
When a response is unfamiliar, explore it from the outside in: print the keys, pick one, print what's inside it, and repeat. That is exactly how the last line of the cell was worked out.
3.7 Building prompts from data
A prompt for an AI model is just text, and much of working with AI in Python is assembling that text from data: an instruction, then the records you want the model to look at.
reviews = [
{"id": 1, "text": "Lovely board but it took two weeks to arrive."},
{"id": 2, "text": "The handle snapped after a week."},
{"id": 3, "text": "Perfect gift, beautifully packaged!"},
]
lines = [f"{r['id']}. {r['text']}" for r in reviews] # one numbered line per review
prompt = f"""You are helping a small kitchenware shop.
Summarise the main complaint in each review below in five words or fewer.
Answer with one line per review, starting with its number.
Reviews:
{chr(10).join(lines)}"""
print(prompt)
print("---")
print(len(prompt), "characters, roughly", len(prompt) // 4, "tokens")
Three things here are worth copying. A triple-quoted f-string lets a prompt run over several lines with data dropped in. Numbering the items lets you match the model's answers back to your records. And printing the finished prompt before sending it is the cheapest check there is: most disappointing AI output traces back to a prompt that didn't say what its author thought it said. (chr(10) is a line break; f-strings don't allow a backslash inside the braces in older versions of Python.)
3.8 One record per line: JSON Lines
Datasets for AI are often stored as JSON Lines (.jsonl): one JSON object per line. Unlike one big JSON file, it can be read and written a line at a time, so it works for files too large to hold in memory, and one damaged line doesn't spoil the rest.
with open("reviews.jsonl", "w", encoding="utf-8") as f:
for r in reviews:
f.write(json.dumps(r) + "\n")
f.write("this line is damaged\n") # simulate a corrupt record
loaded, skipped = [], 0
with open("reviews.jsonl", encoding="utf-8") as f:
for line in f:
try:
loaded.append(json.loads(line))
except json.JSONDecodeError:
skipped += 1
print(len(loaded), "records loaded,", skipped, "skipped")
print(loaded[0])
Counting what you skipped matters as much as skipping it. A loader that silently drops bad lines will one day drop half a file without anyone noticing.
Write a function that finds every order number in the format GFY-##### (five digits) in a piece of text and returns them as a list.
Your turnimport re
message = "Orders GFY-10422 and GFY-10423 are late; GFY-99 is invalid"
# Write your function here, then press RunShow a solution
import re
def find_orders(text):
return re.findall(r"GFY-\d{5}", text)
print(find_orders("Orders GFY-10422 and GFY-10423 are late; GFY-99 is invalid"))
# ['GFY-10422', 'GFY-10423']The starter code holds an API-style response containing two tool calls. Print the name of each tool that was called and the product it was asked about. Then print the total number of tokens used (input plus output).
Your turnreply = {
"content": [
{"type": "text", "text": "Let me check the stock."},
{"type": "tool_use", "name": "check_stock", "input": {"product": "bamboo board"}},
{"type": "tool_use", "name": "check_price", "input": {"product": "utensil set"}},
],
"usage": {"input_tokens": 310, "output_tokens": 64},
}
# Loop over reply["content"], then press RunShow a solution
reply = {
"content": [
{"type": "text", "text": "Let me check the stock."},
{"type": "tool_use", "name": "check_stock", "input": {"product": "bamboo board"}},
{"type": "tool_use", "name": "check_price", "input": {"product": "utensil set"}},
],
"usage": {"input_tokens": 310, "output_tokens": 64},
}
for block in reply["content"]:
if block["type"] == "tool_use":
print(block["name"], "->", block["input"]["product"])
usage = reply["usage"]
print("Total tokens:", usage["input_tokens"] + usage["output_tokens"])Key takeaways
- Use with open(..., encoding='utf-8') for files.
- json.loads parses JSON text; json.dumps creates it.
- Wrap parsing in try/except — AI output isn't always valid JSON.
- re finds and cleans patterns in text.
- csv handles simple tables; pandas handles the rest.
- Explore unfamiliar JSON from the outside in: keys first, then one level at a time.
- A prompt is text assembled from data; print it before you send it.