Skip to content
Kuza Ndoto Academy

Working with CSV & JSON

Beginner → IntermediateChapter 7 · Page 36 of 564 min readUpdated 15 Nov 2026

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.

Common mistake

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)
['name', 'county', 'score'] ['Akinyi', 'Kisumu', '88'] ['Mutua', 'Machakos', '74'] ['Wanjiru', 'Nyeri, Central', '91']

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:,}")
2026-03-01 Mandazi: KES 400 2026-03-01 Chai: KES 750 2026-03-02 Mandazi: KES 550 Total revenue: KES 1,700

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:

PythonJSON
dictobject { }
list, tuplearray [ ]
strstring (always double quotes)
int, floatnumber
True / Falsetrue / false
Nonenull

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))
{"name": "Akinyi", "age": 19, "courses": ["Python", "Maths"], "graduated": false, "mentor": null} { "name": "Akinyi", "age": 19, "courses": [ "Python", "Maths" ], "graduated": false, "mentor": null }
import json

reply = '{"city": "Kampala", "population": 1680000, "capital": true}'
data = json.loads(reply)            # JSON string -> Python

print(type(data))
print(data["city"], data["capital"])
<class 'dict'> Kampala True

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)
['en', 'sw'] True

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))
{"greeting": "Habari, Zoë"} {"greeting": "Habari, Zoë"}
Common mistake

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)
Invalid JSON: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Warning

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?

CSVJSON
ShapeFlat table of rows and columnsNested objects and lists
TypesEverything is textStrings, numbers, booleans, null
Opens in ExcelYesNot directly
Typical useSales records, marks, exportsWeb 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 csv module with newline=""; values come back as strings.
  • DictReader and DictWriter let you work with column names.
  • json.dumps/loads work with strings; json.dump/load work with files.
  • Use indent=2 for readable JSON and ensure_ascii=False to keep accented characters.
Up next · Files & ErrorsExceptionsWhat errors are and why programs crash.
→

Tip: use the ← and → keys to move between pages.