Skip to content
Visual explainer 3h to learn 4 steps

Working with CSV & JSON data

Load, clean, summarise and export tabular and JSON data.

By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.

Topic 29 of 34

In short

CSV is the common format for tables and JSON for nested data. Python's csv and json modules read them into lists and dicts, so you can clean, summarise and export data with the tools you already know.

Explained simply

A lot of real data arrives as files. Bank statements, sales reports and exports from spreadsheets are usually CSV files: plain text where each line is a row and commas separate the columns. Data from websites and apps is usually JSON, which can hold lists inside objects inside lists.

Python has a built-in module for each. The csv module reads a CSV file row by row, so you never have to split lines yourself. The json module turns JSON text into normal Python dicts and lists, and turns them back into text when you save.

Real files are messy. Some cells have extra spaces, some numbers use commas like 1,234.50, some rows are empty or broken. Cleaning means fixing what you can, skipping what you cannot, and counting what you skipped so nothing disappears silently.

Once the data is clean, summarising it is just the dict and list skills you already have: add up totals per group, count how often things appear, sort, and pick the top results. Then save the answer as JSON or CSV for the next program or person.

Press Play on a diagram to walk through it one step at a time.

FlowFrom messy CSV to JSON summary
  1. Step 1
    csv.DictReader

    Each row becomes a dict keyed by header

  2. Step 2
    Clean fields

    strip() text, convert numbers, skip bad rows

  3. Step 3
    Summarise

    Totals per group with a dict or Counter

  4. Step 4
    json.dump

    Write the result to a .json file

CompareCSV vs JSON
CSV
  • Flat rows and columns
  • Every value is text
  • Opens in spreadsheets
  • csv.DictReader / DictWriter
JSON
  • Nested objects and lists
  • Has numbers, booleans, null
  • Common for APIs
  • json.load / json.dump
MapKinds of messy data and the fix
Messy CSV cell
  • Extra spaces
    • " north "
    • Fix: strip()
  • Formatted numbers
    • "1,234.50" or "$12"
    • Fix: remove symbols, then float()
  • Missing values
    • "" or "N/A"
    • Fix: skip, default or None
  • Inconsistent text
    • "NORTH", "North"
    • Fix: .title() or a mapping dict
  • Dates in many formats
    • "03/01/2026"
    • Fix: datetime.strptime

In depth

Why the csv module beats split(",")

A CSV cell may contain a comma, a quote or even a line break. The format handles this with quoting: "Pune, India" is one cell, and a quote inside a quoted cell is written twice, like """. line.split(",") breaks on these cases, while csv.reader and csv.DictReader follow the rules for you.

Always open CSV files with newline="". This lets the csv module see the real line endings, so a line break inside a quoted cell stays inside that cell. Files saved by Excel often start with an invisible byte order mark (BOM); open them with encoding="utf-8-sig" or your first header will look like \ufeffdate. Files that use semicolons or tabs need delimiter=";" or delimiter="\t". If you do not know the format, csv.Sniffer().sniff(sample) can guess the dialect from a sample of text.

  • csv.reader gives lists; csv.DictReader gives dicts keyed by the header
  • Rows with extra cells put the extras under the key None (restkey)
  • Short rows fill missing keys with None (restval)
CompareOne line, two ways to split it
line.split(",")
  • "Pune, India" becomes two cells
  • Quote characters stay in the text
  • Line breaks inside cells break rows
  • Column count changes row to row
csv.reader
  • "Pune, India" stays one cell
  • Quotes are removed correctly
  • Multi-line cells are kept whole
  • Same column count every row

Cleaning and converting messy fields

Every value from the csv module is a str, so cleaning is a set of small string steps before conversion. strip() removes spaces and stray newlines. An empty string after strip() usually means missing data: decide whether to skip the row, use a default, or store None. For numbers, remove thousands separators and currency signs first: "1,234.50".replace(",", "") then float(). For dates, datetime.strptime("03/01/2026", "%d/%m/%Y") parses a known format; check which order (day or month first) the file uses.

For money, floats can show tiny errors (0.1 + 0.2 is 0.30000000000000004). decimal.Decimal("19.99") keeps exact cents, which matters when totals must match a bank statement. Put each conversion in a small function that raises ValueError on bad input, then catch it in the loop, count the bad row and keep its line number (reader.line_num) for a report.

  • Normalise text with strip().lower() or .title() before grouping
  • Keep a list of rejected rows instead of silently dropping them
  • Convert once, early, then work only with clean types

Summarising with dicts, defaultdict and Counter

Most summaries are "for each group, combine the values". A plain dict works with totals[key] = totals.get(key, 0) + amount. collections.defaultdict(list) creates an empty list for new keys, so you can group whole rows: groups[row["region"]].append(row). Counter is a dict built for counting: Counter(words) counts items, counter[key] += 1 never raises KeyError, and counter.most_common(3) returns the top three as (key, count) pairs.

For sorted output use sorted(totals.items(), key=lambda kv: kv[1], reverse=True). For averages, keep both a sum and a count per group, then divide at the end. These tools handle files of millions of rows, because DictReader reads one row at a time and only the small summary stays in memory.

FlowOne row through a grouped summary
  1. 1
    Row dict

    {"region": " north ", "amount": "1,200"}

  2. 2
    Clean

    region North, amount 1200.0

  3. 3
    Group key

    totals["North"]

  4. 4
    Combine

    Add to sum, add 1 to count

  5. 5
    After the loop

    Sort and pick the top groups

How JSON maps to Python types

json.load(f) reads from an open file and json.loads(text) reads from a string; json.dump and json.dumps do the reverse. JSON objects become dicts, arrays become lists, true/false become True/False and null becomes None. Going the other way, tuples become arrays, so they come back as lists.

Three things surprise people. Object keys are always strings in JSON, so {1: "a"} is saved as {"1": "a"}. Dates, Decimals, sets and dataclasses are not JSON types: json.dump raises TypeError unless you convert them, for example with default=str or by building a plain dict first. And by default non-ASCII text is escaped as \u codes; pass ensure_ascii=False to keep it readable. Invalid JSON raises json.JSONDecodeError, which is a subclass of ValueError and tells you the line and column.

  • json.dump(data, f, indent=2, ensure_ascii=False)
  • json.dumps(obj, default=str) for dates and Decimals
  • float("nan") is written as NaN, which strict JSON parsers reject

Writing CSV output correctly

csv.DictWriter(f, fieldnames=[...]) writes dicts as rows in the column order you choose. Call writer.writeheader() once, then writer.writerow(row) or writer.writerows(rows). Open the output with newline="" too, otherwise Windows can add a blank line between rows. If a dict has keys that are not in fieldnames, DictWriter raises ValueError; pass extrasaction="ignore" to drop them on purpose.

The writer quotes cells that contain commas or quotes automatically, so the file opens correctly in a spreadsheet. If people will open the file in Excel and it contains non-English text, writing with encoding="utf-8-sig" adds the BOM that helps Excel detect UTF-8. Choose CSV when the result is a flat table for humans; choose JSON when another program will read it or the data is nested.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Read CSV files with the csv module~45m
  2. 2
    Clean and convert messy fields~45m
  3. 3
    Summarise data with dicts and Counter~45m
  4. 4
    Load and dump JSON files~45m

Key points

  • Open CSV files with newline="" and encoding="utf-8".
  • csv values are always strings; convert with int() or float().
  • Wrap conversions in try/except to skip or report bad rows.
  • json.dump(data, f, indent=2) writes readable JSON.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
import csv, json
from collections import Counter

totals = Counter()
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        try:
            amount = float(row["amount"].strip())
        except ValueError:
            continue  # skip bad rows
        totals[row["region"].strip().title()] += amount

with open("summary.json", "w", encoding="utf-8") as f:
    json.dump(dict(totals), f, indent=2)

Clean a bank export and write a tidy CSV

The bank file has spaces, amounts like "1,234.50" and a few broken rows. Step 1: open with utf-8-sig to drop the Excel BOM. Step 2: clean each field in a helper that raises ValueError on bad input. Step 3: write good rows with DictWriter and remember bad line numbers. Step 4: print how many rows were rejected so nothing is lost silently.

python
import csv
from datetime import datetime
def clean(row):
    return {"date": datetime.strptime(row["Date"].strip(), "%d/%m/%Y").date().isoformat(),
            "amount": float(row["Amount"].replace(",", "").strip()),
            "desc": row["Description"].strip()}
bad = []
with open("bank.csv", newline="", encoding="utf-8-sig") as src, \
     open("clean.csv", "w", newline="", encoding="utf-8") as dst:
    reader, writer = csv.DictReader(src), csv.DictWriter(dst, fieldnames=["date", "amount", "desc"])
    writer.writeheader()
    for row in reader:
        try: writer.writerow(clean(row))
        except (ValueError, KeyError, AttributeError): bad.append(reader.line_num)
print(f"{len(bad)} bad rows at lines {bad}")

Flatten nested JSON orders into a CSV table

orders.json holds a list of orders, each with a list of items. A spreadsheet needs one row per item. Step 1: json.load the file into a list of dicts. Step 2: loop over orders, then over each order's items. Step 3: build one flat dict per item that repeats the order id and customer. Step 4: write the rows with DictWriter.

python
import csv, json

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

rows = [
    {"order_id": o["id"], "customer": o["customer"],
     "sku": item["sku"], "qty": item["qty"]}
    for o in orders for item in o["items"]
]

with open("items.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=["order_id", "customer", "sku", "qty"])
    w.writeheader()
    w.writerows(rows)

Quick reference

  • open(path, newline="", encoding="utf-8") for every CSV read or write
  • encoding="utf-8-sig" removes the BOM that Excel adds to the first header
  • csv.DictReader(f, delimiter=";") for semicolon-separated files
  • Counter(...).most_common(5) gives the top five (key, count) pairs
  • defaultdict(list) groups rows: groups[key].append(row)
  • json.load(f) / json.dump(obj, f, indent=2); loads/dumps work on strings
  • json.dumps(obj, default=str) converts dates and Decimals to strings
  • JSON keys are always strings: {1: "a"} comes back as {"1": "a"}

Common mistakes

  • Doing maths on CSV values without converting them from strings.
  • Splitting lines on commas by hand, which breaks on quoted fields.
  • Forgetting that JSON object keys always come back as strings.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your first header reads \ufeffdate instead of date. What is the simplest fix?

Question 2

2What does json.dumps({"when": date(2026, 1, 5)}) do without extra arguments?

Question 3

3Which tool gives the three most frequent categories most directly?

Question 4

4Why open CSV files with newline=""?

Question 5

5A DictWriter gets a row with a key that is not in fieldnames. What happens by default?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Read people.csv (name, city) and print how many people live in each city, most common first.

  2. Exercise 2medium

    From sales.csv (region, amount), write summary.json with the total and average amount per region, skipping rows where amount is not a number.

  3. Exercise 3hard

    Write a function that saves a list of Expense dataclasses (amount: Decimal, spent_on: date) to JSON and loads them back as equal objects.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use pandas instead of the csv module?
For quick analysis of large tables, pandas.read_csv is very convenient. For scripts that need no extra install, or where you want full control over cleaning row by row, the csv module is enough and is always available.
How do I read a CSV file that has no header row?
Use csv.reader to get lists, or pass fieldnames=["date", "amount"] to csv.DictReader so it uses your names instead of the first line.
What is the difference between json.load and json.loads?
json.load reads from an open file object; json.loads (load string) parses a str you already have, such as an API response body.
Why does my CSV have blank lines between rows on Windows?
The file was opened without newline="". The csv writer already writes its own line endings, so Python's newline translation adds an extra one.

Go deeper

ShareXLinkedInWhatsApp