CSV and JSON
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: comma-separated values
A CSV file is a plain-text table: one row per line, values separated by commas, usually with a header row:
name,score,class
Asha,91,A
Ben,48,BIt 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
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:
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
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 thecsvmodule 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
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] # 91The file looks like this — note true and null:
{
"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:
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; andload/dumpfor files,loads/dumpsfor strings.
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.
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.csvimport 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
with open("scores.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
for row in rows:
row["score"] = int(row["score"])
# 2. Average and top student
average = sum(r["score"] for r in rows) / len(rows)
top = max(rows, key=lambda r: r["score"])["name"]
print(f"Average: {average:.1f}, top: {top}")
# 3. Write report.json
passed = [r for r in rows if r["score"] >= 50]
report = {"average": round(average, 1), "top": top, "passed": [r["name"] for r in passed]}
with open("report.json", "w", encoding="utf-8") as f:
json.dump(report, f, indent=2)
# 4. Read it back
with open("report.json", encoding="utf-8") as f:
print(json.load(f)["passed"])
# 5. Write passed.csv
with open("passed.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "score"], extrasaction="ignore")
writer.writeheader()
writer.writerows(passed)
with open("passed.csv", encoding="utf-8") as f:
print(f.read(), end="")Summary
- CSV stores tables as text; use the
csvmodule, neversplit(","), because values can contain commas and quotes. csv.DictReadergives 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 withcsv.writerorcsv.DictWriter. - JSON stores nested dicts and lists;
json.load/json.dumpwork with files,json.loads/json.dumpswith strings. - JSON has no tuples, sets or dates — convert them to lists or strings before saving.