5. Files, Errors & Testing
Saving Data to Files: Text, CSV & JSON
Save and load persistent program data using 'with open(...)', read and write spreadsheet-style .csv files with Python's csv module, and store structured lists/dicts in .json.
- Read, write, and append plain text files safely using with open(...)
- Parse spreadsheet-style .csv files cleanly with csv.DictReader
- Save and reload structured lists and dictionaries using json
Every list or dictionary you create inside a script vanishes the instant the program finishes running. To save notes, expenses, or high scores for tomorrow, you write them to files.
Python makes working with the three most common file formats—plain .txt, spreadsheet .csv, and web-friendly .json—straightforward.
Plain Text Files with with open(...)
Python RAM (Temporary)
tasks = [...]
Hard Drive (Permanent)
tasks.json / .csv
Variables disappear when a script closes. Saving with `with open(...)` writes data permanently to disk.
Whenever you open a file, always use a with block. with acts like an automatic door closer: the moment the indented lines finish (or even if an error occurs), Python flushes and closes the file safely.
Pick the mode letter carefully:
"r"(Read): Opens an existing file (crashes if missing)."w"(Write): Creates a brand-new file (careful: erases previous contents if the file already exists!)."a"(Append): Adds new text to the bottom without erasing existing lines.
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("Day 1: Variables and loops\n")
file.write("Day 2: Functions and lists\n")
with open("notes.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())Spreadsheet Data with .csv (csv.DictReader)
A CSV (Comma-Separated Values) file looks like this—it opens directly in Excel or Google Sheets:
name,track,score
Alex,Python,92
Maya,SQL,88Never split CSV rows manually with .split(",") (what if someone's note has a comma inside quotes?). Use Python's built-in csv module, which turns every row straight into a dictionary using the header row as keys!
import csv
import io
csv_text = "name,track,score\nAlex,Python,92\nMaya,SQL,88"
reader = csv.DictReader(io.StringIO(csv_text))
for row in reader:
print(f"{row['name']} ({row['track']}): {row['score']}")On your computer, replace io.StringIO(csv_text) with open("students.csv", "r", encoding="utf-8"):
with open("students.csv", "r", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
print(row["name"], row["score"])Saving Python Lists & Dicts with .json
For app data like settings or nested lists of dictionaries, JSON is the cleanest format because numbers stay numbers and booleans stay booleans:
import json
tasks = [
{"title": "Study CSV module", "done": True},
{"title": "Write unit tests", "done": False},
]
# Save Python -> JSON file
with open("tasks.json", "w", encoding="utf-8") as f:
json.dump(tasks, f, indent=2)
# Load JSON file -> Python
with open("tasks.json", "r", encoding="utf-8") as f:
loaded = json.load(f)Try Parsing CSV & JSON Live in the Playground
Click “Run Code” to execute this snippet right in your browser.
Quick Checkpoints
Why should you use Python's csv.DictReader instead of calling line.split(',') manually on a .csv file?
Which file mode preserves existing lines and adds new lines to the bottom?