Skip to content
devtoolbox.cc

Python · Chapter 15 of 21

Python CSV, JSON, TOML, SQLite and ZIP files

14 min study · Examples checked with Python 3.14 and 3.15 ·

Plain text files are a start, but most data has structure: a table of learners, a nested API response, a configuration file, a set of records you query. Python’s standard library handles the common formats without any installs. This chapter walks one small data set, learner progress, through CSV, JSON, TOML, an SQLite database and a ZIP archive, and points out what each format keeps and what it loses.

CSV for tables

import csv
from pathlib import Path

rows = [{"name": "Ada", "done": 4}, {"name": "Lee, Grace", "done": 2}]
path = Path("progress.csv")

with path.open("w", encoding="utf-8", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "done"])
    writer.writeheader()
    writer.writerows(rows)

print(path.read_text(encoding="utf-8"))
# name,done
# Ada,4
# "Lee, Grace",2

with path.open(encoding="utf-8", newline="") as f:
    loaded = [{"name": r["name"], "done": int(r["done"])} for r in csv.DictReader(f)]
print(loaded == rows)  # True

The csv module quotes values that contain commas, quotes or line breaks, which is why "Lee, Grace" survives the round trip. Building CSV lines with ",".join(...) breaks on exactly those values. Open CSV files with newline="" and let the module handle line endings.

CSV has no types: everything comes back as a string, so convert each column you need and expect bad values. Files from spreadsheets may use ; as the delimiter (pass delimiter=";") or a different encoding; Excel’s “CSV UTF-8” adds a byte-order mark that encoding="utf-8-sig" removes. When exporting user text for spreadsheets, be aware that cells starting with =, +, - or @ can be treated as formulas.

JSON for nested data

import json
from datetime import date

report = {"course": "Python", "learners": rows, "published": True, "rating": None}
text = json.dumps(report, indent=2, ensure_ascii=False)
print(json.loads(text)["learners"][1])   # {'name': 'Lee, Grace', 'done': 2}

def to_json(value):
    if isinstance(value, date):
        return value.isoformat()
    raise TypeError(f"cannot serialize {type(value).__name__}")

print(json.dumps({"start": date(2026, 11, 14)}, default=to_json))  # {"start": "2026-11-14"}
try:
    json.loads('{"course": "Python",}')
except json.JSONDecodeError as error:
    print(error.msg, "at line", error.lineno, "column", error.colno)
# Illegal trailing comma before end of object at line 1 column 20

JSON maps to Python directly: objects become dictionaries, arrays become lists, true/false/null become True/False/None. Some things don’t survive: tuples come back as lists, dictionary keys always become strings, and dates, Decimal and your own classes can’t be written at all unless you pass a default function that converts them, as above. Use json.dump(obj, f) and json.load(f) with open files.

A JSONDecodeError carries the line and column of the problem. Parsing only checks syntax; whether the data has the fields and types you expect is a separate question, which a JSON Schema answers. On this site, the JSON formatter finds syntax errors, the JSON Schema validator checks structure, and the JSON, YAML and CSV converter turns one format into another.

TOML for configuration

TOML is the format of pyproject.toml and many application config files. The standard library reads it with tomllib:

import tomllib

config = tomllib.loads("""
[course]
title = "Python basics"
chapters = 21
start = 2026-11-14

[course.limits]
seats = 30
""")
print(config["course"]["chapters"], config["course"]["start"])  # 21 2026-11-14
print(type(config["course"]["start"]).__name__, config["course"]["limits"])  # date {'seats': 30}

TOML keeps types that JSON lacks: the start value arrives as a real date. tomllib.load reads from a file opened in binary mode ("rb"). The module only reads; to write TOML, install a package such as tomli-w. Configuration is a good use for TOML; data exchange between programs usually uses JSON.

SQLite for records you query

When data grows beyond one file you rewrite each time, or you need to search, update single records or have several processes read it, use a database. SQLite stores a whole database in one file and ships with Python:

import sqlite3

with sqlite3.connect("progress.db") as db:
    db.execute("CREATE TABLE IF NOT EXISTS progress (name TEXT PRIMARY KEY, done INTEGER NOT NULL)")
    db.executemany("INSERT OR REPLACE INTO progress VALUES (:name, :done)", rows)
    db.execute("UPDATE progress SET done = done + 1 WHERE name = ?", ("Ada",))

    wanted = "Lee, Grace'; DROP TABLE progress; --"
    print(db.execute("SELECT done FROM progress WHERE name = ?", (wanted,)).fetchall())  # []
    for name, done in db.execute("SELECT name, done FROM progress ORDER BY done DESC"):
        print(name, done)
# Ada 5
# Lee, Grace 2
db.close()

Always pass values as parameters (? or :name) and never format them into the SQL string. With parameters, the odd-looking wanted value is just a name that doesn’t exist; pasted into the SQL with an f-string, it would delete the table. Using the connection in a with block commits the changes if the block succeeds and rolls them back if it raises, but does not close the connection, hence the explicit close(). The FastAPI and Django tracks build on the same ideas with an ORM.

Python also has pickle and shelve for saving arbitrary Python objects. Loading a pickle can run arbitrary code, so only use them for files your own program wrote, never for uploads or downloads.

ZIP archives

from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile

Path("report.json").write_text(json.dumps(report), encoding="utf-8")
with ZipFile("export.zip", "w", compression=ZIP_DEFLATED) as zf:
    zf.write("report.json", arcname="data/report.json")
    zf.writestr("README.txt", "Progress export\n")

with ZipFile("export.zip") as zf:
    print(zf.namelist())                       # ['data/report.json', 'README.txt']
    with zf.open("data/report.json") as member:
        print(json.load(member)["course"])     # Python

arcname sets the path inside the archive, so your local folder structure doesn’t leak into it. writestr adds a file from a string without touching the disk, and zf.open reads a member as a binary stream (json.load accepts bytes) without extracting anything. The zipfile module can read some password-protected archives but cannot create encrypted ones; for confidential data, encrypt with a dedicated tool.

Treat archives from other people as untrusted. Before extracting, check the number of members, their uncompressed sizes (a tiny ZIP can expand to gigabytes) and their names, since a member called ../../.bashrc would land outside the target folder. ZipFile.extractall cleans dangerous names, but size limits are your job.

Practice

Read progress.csv back, add a rating column (an integer from 1 to 5, or empty), and write the result both as JSON and into the SQLite table (add a nullable rating INTEGER column). Then put the JSON file into a ZIP archive as exports/progress.json and read it back without extracting.

Answer check: empty CSV cells come back as "", which you should convert to None; JSON then writes null and SQLite stores NULL. Use ALTER TABLE progress ADD COLUMN rating INTEGER once, and parameters for every insert. The ZIP member name must be exactly exports/progress.json.

Summary

CSV is for flat tables and returns strings; JSON is for nested data and needs help with dates; TOML is for configuration and keeps types; SQLite is for records you query and update, always with parameters; ZIP bundles files and must be inspected before extraction when it comes from elsewhere. Parsing checks syntax only, so validate the data afterwards.

All Python chapters