Loading the lesson
Loading the lesson
AI & ML Engineering · Programming Foundations · Lesson 7 of 10
Reading and writing files, working with JSON, and handling errors without crashing.
Read the short notes and pictures.Do everything inside a blue frame.
Memory is cleared when a program ends. To keep data, or send it to another program, you write it as text. JSON is the most common format for that.
In Python (a dict)
{
"name": "Asha",
"age": 28,
"active": True,
"tags": ["ml", "ai"]
}As JSON (text)
{
"name": "Asha",
"age": 28,
"active": true,
"tags": ["ml", "ai"]
}1import json23user = {"name": "Asha", "age": 28}4with open("user.json", "w") as f:5json.dump(user, f)67with open("user.json") as f:8loaded = json.load(f)9print(loaded["name"])
Press Next to run the first line.
Memory
Nothing yet
Output
What does the with block do for you?
When a line cannot do what it was asked, Python raises an error. try and except let the program carry on.
1text = "abc"2try:3number = int(text)4print(number)5except ValueError:6number = 07print("Not a number")8print(number)
Press Next to run the first line.
Memory
Nothing yet
Output
FileNotFoundError
open("missing.txt")The file is not there.
ValueError
int("abc")Right type, wrong content.
KeyError
user["email"]The dict has no such key.
TypeError
"5" + 5The types do not go together.
data = {"name": "Asha"} then data["age"]. Which error?
Open "notes.txt" and print what is in it. If the file does not exist, print "No notes yet" instead of crashing.
Hint: f.read() returns the whole file as one string.
A pattern you will use again and again: load a list from a JSON file, add to it, write it back. The first time the file is not there yet, so start with an empty list.
1import json23try:4with open("journal.json") as f:5readings = json.load(f)6except FileNotFoundError:7readings = []89readings.append({"city": "Pune", "temp": 27.4})1011with open("journal.json", "w") as f:12json.dump(readings, f, indent=2)13print(len(readings), "saved")
Press Next to run the first line.
Memory
Nothing yet
Output
Write two functions: load(path) returns the list saved in a JSON file, or an empty list when the file is missing. add(item, path) loads the list, appends item, saves it and returns the new length.
Hint: add can call load. Then open the file with "w" and json.dump the list.
Practice: files, JSON and errors
Save the list [{"city": "Pune", "temp": 27.4}] to a file called readings.json, then load it back into a variable loaded.
Press Run to see the output here.
A CSV file is a table where each line is a row and commas separate the columns. Spreadsheets export it, and Python reads it with the csv module.
expenses.csv
date,category,amount 2026-11-01,food,240 2026-11-02,travel,90 2026-11-02,food,120
Reading it
import csv
with open("expenses.csv") as f:
for row in csv.DictReader(f):
print(row["category"], row["amount"])row["amount"] is "240". What does row["amount"] + row["amount"] give?
Keep these