CSV and JSON

Topic 4 of 4 in Errors and files6 min readBeginnerFree course

Overview

Most data you’ll handle comes in one of two text formats: CSV, for tables (exported from spreadsheets and databases), and JSON, for nested data (web APIs, configuration files, saved app state). Python’s standard library reads and writes both.

CSV and JSON: data in and out. scores.csv holds rows and columns: name,score then Asha,91 and Ben,78. scores.json holds nested data: [{“name”: “Asha”, “score”: 91}, {“name”: “Ben”, “score”: 78}]. csv.DictReader and json.load turn either file into the same Python data, a list of dictionaries such as [{“name”: “Asha”, “score”: 91}, …]; json.dump(data, f, indent=2) and csv.DictWriter write it back out.

CSV: comma-separated values

A CSV file is a plain-text table: one row per line, values separated by commas, usually with a header row:

Text
name,score,class
Asha,91,A
Ben,48,B

It looks simple enough to parse with line.split(",") — but real CSV files contain values like "Rao, Asha" (a comma inside quotes) or line breaks inside a field. The csv module handles all of that correctly. Always use it.

Reading rows as dictionaries

Python
import csv

with open("scores.csv", encoding="utf-8", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["score"])

DictReader uses the header row as keys, so each row is a dictionary: {"name": "Asha", "score": "91", "class": "A"}.

Every value is a string. Convert the columns you calculate with: int(row["score"]).

Pass newline="" when opening CSV files — the csv module handles line endings itself, and this avoids blank lines appearing on Windows.

Reading rows as lists

csv.reader gives each row as a list instead — useful for files without headers:

Python
with open("scores.csv", encoding="utf-8", newline="") as f:
    reader = csv.reader(f)
    header = next(reader)          # ['name', 'score', 'class']
    for name, score, group in reader:
        ...

Writing CSV

Python
rows = [{"name": "Asha", "score": 91}, {"name": "Ben", "score": 48}]

with open("out.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "score"])
    writer.writeheader()
    writer.writerows(rows)

csv.writer(f).writerow(["Asha", 91]) writes lists. The writer adds quotes wherever a value needs them.

If your dictionaries have extra keys not in fieldnames, DictWriter raises a ValueError — pass extrasaction="ignore" to drop them.

Spreadsheet tips

  • Excel sometimes saves CSV with a hidden “byte order mark” at the start; open such files with encoding="utf-8-sig".
  • Some countries’ spreadsheets use semicolons: csv.reader(f, delimiter=";").
  • For serious data analysis, the pandas library (pd.read_csv) is the standard tool — but the csv module is all you need for everyday scripts.

JSON: JavaScript Object Notation

JSON represents nested data with objects ({}), arrays ([]), strings, numbers, true/false and null. It maps almost one-to-one onto Python:

JSON Python
object {"a": 1} dict
array [1, 2] list
string "hi" str
number 1, 1.5 int, float
true / false True / False
null None

Saving and loading

Python
import json

data = {"user": "Asha", "scores": [91, 85], "premium": True, "manager": None}

with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)          # indent makes it readable

with open("data.json", encoding="utf-8") as f:
    loaded = json.load(f)

loaded["scores"][0]       # 91

The file looks like this — note true and null:

JSON
{
  "user": "Asha",
  "scores": [
    91,
    85
  ],
  "premium": true,
  "manager": null
}

Strings instead of files

The functions ending in s work with strings — handy for web APIs:

Python
text = json.dumps(data)                 # dict → JSON string
back = json.loads('{"ok": true}')       # JSON string → {'ok': True}

(Remember: load/dump for files, loads/dumps for strings.)

What JSON can’t store

  • Tuples come back as lists.
  • Sets and dates raise TypeError: Object of type set is not JSON serializable. Convert them first: list(my_set), my_date.isoformat().
  • Dictionary keys are always strings in JSON: {1: "a"} comes back as {"1": "a"}.

Invalid JSON

Malformed JSON — a trailing comma, single quotes — raises json.JSONDecodeError (a kind of ValueError), with the line and column of the problem. Catch it when loading files people edit by hand.

CSV or JSON?

  • CSV — flat tables, every row the same columns, opened in spreadsheets.
  • JSON — nested or irregular data, configuration, anything sent to or from a web API.

Remember: use the modules, not split; convert CSV values from strings; and load/dump for files, loads/dumps for strings.

Exercise

From spreadsheet to report

Your program starts by writing the scores.csv file in the starter. Then: (1) read it with csv.DictReader, converting each score to an int; (2) print the average score to 1 decimal place and the top student; (3) write report.json containing {"average": …, "top": …, "passed": [names with 50 or more]} with indent=2; (4) read report.json back with json.load and print the passed list; (5) write passed.csv with csv.DictWriter containing only the name and score of students who passed, then print its contents.

Python
import csv
import json

with open("scores.csv", "w", encoding="utf-8", newline="") as f:
    f.write("name,score,class\nAsha,91,A\nBen,48,B\nChen,85,A\nDee,62,B\n")

# 1. Read with DictReader

# 2. Average and top student

# 3. Write report.json

# 4. Read it back

# 5. Write passed.csv

Summary

  • CSV stores tables as text; use the csv module, never split(","), because values can contain commas and quotes.
  • csv.DictReader gives each row as a dict keyed by the header; every value is a string — convert numbers yourself.
  • Open CSV files with newline="" and write rows with csv.writer or csv.DictWriter.
  • JSON stores nested dicts and lists; json.load/json.dump work with files, json.loads/json.dumps with strings.
  • JSON has no tuples, sets or dates — convert them to lists or strings before saving.