Working with CSV & JSON
CSV and JSON are the two data formats you'll meet most often. CSV stores tables (think spreadsheets), and JSON stores nested data (think web APIs and settings files). Python's standard library reads and writes both.
CSV: comma-separated values
A CSV file is plain text where each line is a row and commas separate the columns. The first row usually holds the column names. Excel, Google Sheets and most databases can export CSV.
Writing a CSV file
import csv
rows = [
["name", "county", "score"],
["Akinyi", "Kisumu", 88],
["Mutua", "Machakos", 74],
["Wanjiru", "Nyeri, Central", 91],
]
with open("results.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)
The file results.csv now contains:
name,county,score Akinyi,Kisumu,88 Mutua,Machakos,74 Wanjiru,"Nyeri, Central",91
Notice that "Nyeri, Central" was wrapped in quotes automatically because it contains a comma. This is exactly why you should use the csv module instead of joining strings with commas yourself.
Always open CSV files with newline="". Without it, Windows can end up with an extra blank line between every row, because the csv module writes its own line endings.
Reading with csv.reader
import csv
with open("results.csv", newline="", encoding="utf-8") as file:
reader = csv.reader(file)
header = next(reader) # take the first row
print(header)
for row in reader:
print(row)
Each row is a list of strings, even the scores. Convert them with int() or float() before doing maths.
Reading with csv.DictReader
DictReader uses the header row as keys, so each row becomes a dictionary. Your code then says row["price"] instead of the less readable row[3]. Suppose a kiosk records its sales in sales.csv:
date,item,quantity,price 2026-03-01,Mandazi,40,10 2026-03-01,Chai,25,30 2026-03-02,Mandazi,55,10
import csv
total = 0
with open("sales.csv", newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
revenue = int(row["quantity"]) * int(row["price"])
total += revenue
print(f"{row['date']} {row['item']}: KES {revenue}")
print(f"Total revenue: KES {total:,}")
Writing with csv.DictWriter
import csv
menu = [
{"item": "Mandazi", "price": 10},
{"item": "Chai", "price": 30},
]
with open("menu.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["item", "price"])
writer.writeheader()
writer.writerows(menu)
Resulting menu.csv:
item,price Mandazi,10 Chai,30
JSON: JavaScript Object Notation
JSON looks very like Python dictionaries and lists. It's the language web APIs speak, and it's ideal for saving settings or app data that has nested structure. Python types map to JSON like this:
| Python | JSON |
|---|---|
dict | object { } |
list, tuple | array [ ] |
str | string (always double quotes) |
int, float | number |
True / False | true / false |
None | null |
Converting to and from strings: dumps and loads
import json
student = {
"name": "Akinyi",
"age": 19,
"courses": ["Python", "Maths"],
"graduated": False,
"mentor": None,
}
text = json.dumps(student) # Python -> JSON string
print(text)
print(json.dumps(student, indent=2))
import json
reply = '{"city": "Kampala", "population": 1680000, "capital": true}'
data = json.loads(reply) # JSON string -> Python
print(type(data))
print(data["city"], data["capital"])
Remember: the functions ending in s (dumps, loads) work with strings. The ones without (dump, load) work with files.
Saving and loading a JSON file
import json
settings = {"theme": "dark", "font_size": 14, "languages": ["en", "sw"]}
with open("settings.json", "w", encoding="utf-8") as file:
json.dump(settings, file, indent=2)
with open("settings.json", encoding="utf-8") as file:
loaded = json.load(file)
print(loaded["languages"])
print(loaded == settings)
The file settings.json looks like this:
{
"theme": "dark",
"font_size": 14,
"languages": [
"en",
"sw"
]
}
Non-English characters
By default, json escapes non-ASCII characters. Pass ensure_ascii=False to keep them readable.
import json
print(json.dumps({"greeting": "Habari, Zoë"}))
print(json.dumps({"greeting": "Habari, Zoë"}, ensure_ascii=False))
JSON requires double quotes. Text that uses single quotes, like a printed Python dictionary, is not valid JSON:
import json
try:
json.loads("{'name': 'Ali'}")
except json.JSONDecodeError as error:
print("Invalid JSON:", error)
JSON object keys are always strings. A dictionary with integer keys comes back with string keys: json.loads(json.dumps({1: "one"})) gives {'1': 'one'}. Tuples also come back as lists.
CSV or JSON?
| CSV | JSON | |
|---|---|---|
| Shape | Flat table of rows and columns | Nested objects and lists |
| Types | Everything is text | Strings, numbers, booleans, null |
| Opens in Excel | Yes | Not directly |
| Typical use | Sales records, marks, exports | Web APIs, settings, app data |
When you move into data analysis, pandas can load both formats in one line; see Loading Data. The Budget Tracker project uses JSON to save its records.
Key points
- Use the
csvmodule withnewline=""; values come back as strings. DictReaderandDictWriterlet you work with column names.json.dumps/loadswork with strings;json.dump/loadwork with files.- Use
indent=2for readable JSON andensure_ascii=Falseto keep accented characters.
Tip: use the ← and → keys to move between pages.
