PY-101 ยท Files and errors
CSV and JSON
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
CSV stores rows and columns as text with commas, like a spreadsheet, and Python's csv module reads and writes it. JSON stores nested data such as dictionaries and lists, and json.dumps / json.loads convert between Python objects and JSON text. Most data you exchange with spreadsheets and web APIs is in one of the two.
- Write and read CSV with the csv module
- Read rows as dictionaries
- Convert to and from JSON
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import csv, jsonwith open("sales.csv", "w", newline="") as f:w = csv.writer(f)w.writerow(["item", "qty"])w.writerow(["tea", 3])w.writerow(["milk", 5])with open("sales.csv", newline="") as f:rows = list(csv.DictReader(f))total = sum(int(r["qty"]) for r in rows)print(rows[0], total)text = json.dumps({"total": total, "items": [r["item"] for r in rows]})print(text)print(json.loads(text)["items"][1])
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
{'item': 'tea', 'qty': '3'} 8
{"total": 8, "items": ["tea", "milk"]}
milk ๐ฏ Parse the JSON text, add 1 to the "visits" value, and print the updated data as JSON. Expected: {"page": "home", "visits": 42}
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
data = json.loads(text); data["visits"] += 1; print(json.dumps(data))
- The problemFinance sends you a spreadsheet export as CSV; a web API sends you JSON. Your script needs to read both, combine them and save a result.
- The Python idea
import csv, jsonCSV stores rows and columns as text with commas, like a spreadsheet, and Python's csv module reads and writes it. - In real lifeMost "automate my report" scripts read a CSV export, total some columns and send the result as JSON to another system.
Start with a question
Finance sends you a spreadsheet export as CSV; a web API sends you JSON. Your script needs to read both, combine them and save a result.
Exports, imports, configs and APIs all use CSV or JSON. Reading them is one of the most common jobs in Python.
Explain it like I'm 10
CSV is a table written with commas. JSON is a set of labelled boxes inside boxes. Python can read and write both.
The technical explanation
csv.writer(f).writerow([...]) writes one row. Open the file with newline="" so rows are not doubled on Windows.
csv.DictReader(f) reads each row as a dict keyed by the header row.
json.dumps(data, indent=2) turns Python into JSON text; json.loads(text) turns it back.
Syntax
import csv, json
csv.writer(f).writerow(row)
for row in csv.DictReader(f): ...
json.dumps(obj) json.loads(text) Real-world scenario
Most "automate my report" scripts read a CSV export, total some columns and send the result as JSON to another system.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: try, except and finally โQuestions people ask
What is the difference between json.load and json.loads?
json.load reads JSON from a file object; json.loads reads it from a string. Likewise json.dump writes to a file and json.dumps returns a string.
Should I use pandas for CSV files?
For quick scripts the csv module is enough. For analysis, filtering and joining large tables, pandas.read_csv is much easier.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between json.load and json.loads?
json.load reads JSON from a file object; json.loads reads it from a string. Likewise json.dump writes to a file and json.dumps returns a string.
beginner Should I use pandas for CSV files?
For quick scripts the csv module is enough. For analysis, filtering and joining large tables, pandas.read_csv is much easier.
intermediate What type are values read by csv.DictReader?
Strings. CSV values are text.
intermediate json.loads does what?
JSON text โ Python object. loads = load from a string.
Quick revision
Remember
- Write and read CSV with the csv module
- Read rows as dictionaries
- Convert to and from JSON
- csv reads every value as text. Convert numbers with int() or float() before doing maths.
Syntax
import csv, json
csv.writer(f).writerow(row)
for row in csv.DictReader(f): ...
json.dumps(obj) json.loads(text) Official documentation
- csv module (docs.python.org)
- json module (docs.python.org)