Mathew K Analytics

Lesson 8 · Python standard library deep dive

Python json & csv Explained: Read and Write Data Files | Standard Library #8

Video eight of the twenty-five-part series: json and csv, the two most common structured text formats for exchanging data. Serializing, parsing, files,…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Python Standard Library Deep-Dive, Video 8: json and csv#

  • Video eight of the twenty-five-part series: json and csv, the two most common structured text formats for exchanging data.
  • Serializing, parsing, files, custom types, and every variant of reading and writing CSV.
  • Let's get into it.

Part 1: What json and csv Offer#

import json
import csv
data = {'name': 'Ana', 'age': 29, 'active': True}
print(json.dumps(data))
{"name": "Ana", "age": 29, "active": true}

Part 2: json.dumps() - Serializing to a String#

record = {
    'id': 1,
    'tags': ['python', 'json'],
    'score': 9.5,
    'verified': True,
    'notes': None
}
print(json.dumps(record))
{"id": 1, "tags": ["python", "json"], "score": 9.5, "verified": true, "notes": null}

Part 3: json.loads() - Parsing from a String#

json_text = '{"name": "Sam", "scores": [85, 90, 78], "passed": true}'
parsed = json.loads(json_text)
print(parsed)
print(type(parsed))
print(parsed['scores'])
print(type(parsed['passed']))
{'name': 'Sam', 'scores': [85, 90, 78], 'passed': True}
<class 'dict'>
[85, 90, 78]
<class 'bool'>

Part 4: json.dump() and json.load() - Files#

data = {'users': ['Ana', 'Sam', 'Lee'], 'count': 3}
with open('demo_data.json', 'w') as f:
    json.dump(data, f)
with open('demo_data.json', 'r') as f:
    loaded = json.load(f)
print(loaded)
print(loaded == data)
{'users': ['Ana', 'Sam', 'Lee'], 'count': 3}
True

Part 5: Handling Non-Native Types#

from datetime import date
try:
    json.dumps({'today': date.today()})
except TypeError as e:
    print(f'Caught: {e}')
Caught: Object of type date is not JSON serializable
def json_default(obj):
    if isinstance(obj, date):
        return obj.isoformat()
    raise TypeError(f'Cannot serialize {type(obj)}')
result = json.dumps({'today': date.today()}, default=json_default)
print(result)
{"today": "2026-08-23"}

Part 6: Formatting Options: indent, sort_keys, separators#

data = {'z_last': 1, 'a_first': 2, 'nested': {'x': 1, 'y': 2}}
print(json.dumps(data, indent=2))
print(json.dumps(data, indent=2, sort_keys=True))
print(json.dumps(data, separators=(',', ':')))
{
  "z_last": 1,
  "a_first": 2,
  "nested": {
    "x": 1,
    "y": 2
  }
}
{
  "a_first": 2,
  "nested": {
    "x": 1,
    "y": 2
  },
  "z_last": 1
}
{"z_last":1,"a_first":2,"nested":{"x":1,"y":2}}

Part 7: csv.reader and csv.writer#

rows = [
    ['name', 'city', 'notes'],
    ['Ana', 'Lima', 'Likes coffee, tea too'],
    ['Sam', 'Reno', 'No notes']
]
with open('demo_data.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(rows)
with open('demo_data.csv', 'r') as f:
    print(f.read())
name,city,notes
Ana,Lima,"Likes coffee, tea too"
Sam,Reno,No notes

with open('demo_data.csv', 'r', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
['name', 'city', 'notes']
['Ana', 'Lima', 'Likes coffee, tea too']
['Sam', 'Reno', 'No notes']

Part 8: csv.DictReader and csv.DictWriter#

records = [
    {'name': 'Ana', 'score': 85},
    {'name': 'Sam', 'score': 92}
]
with open('demo_scores.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['name', 'score'])
    writer.writeheader()
    writer.writerows(records)
with open('demo_scores.csv', 'r') as f:
    print(f.read())
name,score
Ana,85
Sam,92

with open('demo_scores.csv', 'r', newline='') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)
        print(row['name'], row['score'])
{'name': 'Ana', 'score': '85'}
Ana 85
{'name': 'Sam', 'score': '92'}
Sam 92

Part 9: CSV Dialects and Quoting#

with open('demo_tabs.tsv', 'w', newline='') as f:
    writer = csv.writer(f, delimiter='\t')
    writer.writerow(['name', 'role'])
    writer.writerow(['Ana', 'Engineer'])
with open('demo_tabs.tsv', 'r', newline='') as f:
    reader = csv.reader(f, delimiter='\t')
    for row in reader:
        print(row)
['name', 'role']
['Ana', 'Engineer']
with open('demo_quoted.csv', 'w', newline='') as f:
    writer = csv.writer(f, quoting=csv.QUOTE_ALL)
    writer.writerow(['Ana', 30, 'Engineer'])
with open('demo_quoted.csv', 'r') as f:
    print(f.read())
"Ana","30","Engineer"

Part 10: Common Patterns#

def dicts_to_csv(records, filename):
    if not records:
        return
    fieldnames = list(records[0].keys())
    with open(filename, 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(records)
data = [{'product': 'Widget', 'price': 9.99}, {'product': 'Gadget', 'price': 19.99}]
dicts_to_csv(data, 'demo_products.csv')
with open('demo_products.csv', 'r') as f:
    print(f.read())
product,price
Widget,9.99
Gadget,19.99

def load_config(path, defaults=None):
    defaults = defaults or {}
    try:
        with open(path, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return defaults
config = load_config('demo_data.json')
print(config)
missing_config = load_config('genuinely_does_not_exist.json', {'debug': False})
print(missing_config)
{'users': ['Ana', 'Sam', 'Lee'], 'count': 3}
{'debug': False}

Wrap-Up: What You Learned#

  • json.dumps and json.loads convert between Python objects and JSON strings.
  • json.dump and json.load work directly with open files, skipping the intermediate string.
  • The default argument bridges non-native types like dates into JSON-serializable form.
  • Formatting with indent, sort_keys, and separators.
  • csv.reader and csv.writer for plain rows; DictReader and DictWriter for named fields.
  • Dialects and quoting for delimiters other than comma and controlling exactly what gets quoted.
  • Two real patterns: dict-list-to-CSV in a few lines, and safe JSON config loading with a fallback.
  • That wraps up json and csv. Next up: math, random, and statistics, the core numeric modules.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.