Lesson 38 of 60
โฎPrev Nextโฏ

PY-101 ยท Files and errors

CSV and JSON

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

38of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    CSV and JSON, running
    1. import csv, json
    2. with open("sales.csv", "w", newline="") as f:
    3. w = csv.writer(f)
    4. w.writerow(["item", "qty"])
    5. w.writerow(["tea", 3])
    6. w.writerow(["milk", 5])
    7. with open("sales.csv", newline="") as f:
    8. rows = list(csv.DictReader(f))
    9. total = sum(int(r["qty"]) for r in rows)
    10. print(rows[0], total)
    11. text = json.dumps({"total": total, "items": [r["item"] for r in rows]})
    12. print(text)
    13. print(json.loads(text)["items"][1])
    Press โ–ถ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideaimport csv, jsonCSV stores rows and columns as text with commas, like a spreadsheet, and Python's csv module reads and writes it.
    3. 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)

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Most "automate my report" scripts read a CSV export, total some columns and send the result as JSON to another system.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What type are values read by csv.DictReader?
    2. 2. json.loads does what?
    3. 3. Which keeps nested data like lists inside dicts?
    4. 4. Why open CSV files with newline=""?
    5. 5. json.dumps({"a": True})?

    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