Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
CSV is rows of strings, JSON is labelled and nested. Read employees.csv, round-trip JSON and your own objects, process huge files one line or chunk at a time, build a yield pipeline, read TOML with tomllib, and see why pickle can run code.
What you will learn
- Read and write CSV with csv.reader, DictReader and DictWriter, and remember every value is a string
- Serialize to JSON with dumps/loads and dump/load, and handle types JSON doesn't know
- Process files too big for memory line by line, in chunks, and with yield pipelines
- Read TOML settings with tomllib and know why you never unpickle untrusted data
Before you start
- Reading and writing files with open and with
- Dictionaries and lists
- Python classes
So far you've opened files and read them as plain text. But most files have a shape, rows or labelled fields, and Python can read that shape for you.
Think about a register with ruled columns. Every row has the same columns, and each cell holds one thing. That's CSV. Now think about a filled-in form. Every answer sits beside its label, and one answer can be a whole list. That's JSON, the format web APIs send all the time. Both are only text in a file. A flat table suits CSV; anything nested suits JSON.
Reading CSV
Here's the file we'll use, employees.csv:
name,department,salary,city
Alice,Engineering,95000,New York
Bob,Marketing,72000,Chicago
Carol,Engineering,98000,San Francisco
"Diana, Jr.",Sales,65000,Boston
Eve,Marketing,70000,New York
import csv
with open("employees.csv", newline="") as f:
reader = csv.reader(f)
header = next(reader)
print(header)
for row in reader:
print(row)
['name', 'department', 'salary', 'city']
['Alice', 'Engineering', '95000', 'New York']
['Bob', 'Marketing', '72000', 'Chicago']
['Carol', 'Engineering', '98000', 'San Francisco']
['Diana, Jr.', 'Sales', '65000', 'Boston']
['Eve', 'Marketing', '70000', 'New York']
newline="" lets the csv module handle line endings itself. Look at Diana, Jr.: there's a comma inside her name, but it's in double quotes, so it stays one field. Splitting on commas by hand would break this, which is why you use the module. And every value comes back as a string, because CSV has no types.
DictReader: ask by name
import csv
with open("employees.csv", newline="") as f:
employees = list(csv.DictReader(f))
print(employees[0])
print(employees[3]["name"])
print(type(employees[0]["salary"]).__name__)
total = sum(int(e["salary"]) for e in employees)
print(total)
{'name': 'Alice', 'department': 'Engineering', 'salary': '95000', 'city': 'New York'}
Diana, Jr.
str
400000
Each header name rides onto its value, so every row is a dictionary. Salary is still a str, so we convert with int before adding. Use DictReader most of the time; your code says salary instead of row[2].
Writing CSV
import csv
people = [
{"name": "Alice", "city": "New York"},
{"name": "Diana, Jr.", "city": "Boston"},
]
with open("people.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=["name", "city"])
w.writeheader()
w.writerows(people)
with open("people.csv", newline="") as f:
for line in f:
print(line.rstrip())
name,city
Alice,New York
"Diana, Jr.",Boston
newline="" stops Windows adding blank lines between rows, and Python put quotes around "Diana, Jr." on its own. For a tab-separated file, pass delimiter="\t" to the reader.
JSON: dumps and loads
import json
data = {
"name": "Alice",
"active": True,
"boss": None,
"skills": ["Python", "SQL"],
"pair": (1, 2),
}
text = json.dumps(data)
print(text)
back = json.loads(text)
print(back["active"], back["boss"])
print(back["pair"])
print(type(text).__name__, type(back).__name__)
{"name": "Alice", "active": true, "boss": null, "skills": ["Python", "SQL"], "pair": [1, 2]}
True None
[1, 2]
str dict
A Python dictionary looks like JSON, but it's an object in memory. json.dumps turns it into text, which is called serializing. True becomes true, None becomes null, and the tuple becomes a list. json.loads turns the text back, but the pair stays a list because JSON has no tuples. The "s" in both names stands for string.
For files, drop the "s": json.dump(employees, f, indent=2) writes a readable file and json.load(f) reads it back. In the lesson the loaded list compares equal to the original (True), and Bob's active flag comes back as a proper False.
Types JSON doesn't know
import json
from decimal import Decimal
total = Decimal("49.99")
print(json.dumps(total))
Traceback (most recent call last):
File "S04L04_StructuredData\json_default_error.py", line 5, in <module>
print(json.dumps(total))
~~~~~~~~~~^^^^^^^
TypeError: Object of type Decimal is not JSON serializable
JSON only knows text, numbers, true, false, null, lists and objects. Pass a small function as default, and json calls it only for values it doesn't know:
import json
from datetime import time
from decimal import Decimal
order = {
"id": 7,
"total": Decimal("49.99"),
"at": time(9, 30),
}
def to_json(obj):
if isinstance(obj, Decimal):
return str(obj)
if isinstance(obj, time):
return obj.isoformat()
raise TypeError(f"cannot save {type(obj)}")
print(json.dumps(order, default=to_json))
{"id": 7, "total": "49.99", "at": "09:30:00"}
For anything else it raises TypeError, so nothing gets saved wrong without you knowing.
Your own objects
import json
class User:
def __init__(self, name, email, active=True):
self.name = name
self.email = email
self.active = active
user = User("Alice", "[email protected]")
print(json.dumps(user.__dict__))
class UserEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, User):
return {"__user__": True, **obj.__dict__}
return super().default(obj)
text = json.dumps(user, cls=UserEncoder)
print(text)
def as_user(d):
if "__user__" in d:
return User(d["name"], d["email"], d["active"])
return d
restored = json.loads(text, object_hook=as_user)
print(type(restored).__name__, restored.name)
{"name": "Alice", "email": "[email protected]", "active": true}
{"__user__": true, "name": "Alice", "email": "[email protected]", "active": true}
User Alice
user.__dict__ is the quick way. The encoder adds a __user__ label, and object_hook looks at each dictionary json builds and makes a User again when it sees the label. Plain dumps and loads on dictionaries cover most days, so use this only when you need it.
Files too big for memory
Think about a thick book. You don't hold every page up in front of you to read it. But f.read() does just that: it pulls the whole file into memory as one string. A file object works page by page instead.
with open("server.log", "w", newline="\n") as f:
for i in range(1, 10001):
level = "ERROR" if i % 250 == 0 else "INFO"
f.write(f"{i},{level},request {i}\n")
with open("server.log") as f:
print(next(f).strip())
print(next(f).strip())
count = 0
with open("server.log") as f:
for line in f:
if ",ERROR," in line:
count += 1
print(count)
1,INFO,request 1
2,INFO,request 2
40
Each line comes in, gets checked and goes away, so the file can be any size. Files with no lines, like video or images, are read in chunks: while chunk := f.read(8192) on a 20,000-byte file in rb mode gives three chunks, and the total, 20000, matches os.path.getsize.
yield: build your own line-at-a-time functions
def count_up(limit):
n = 1
while n <= limit:
print("making", n)
yield n
n += 1
for value in count_up(3):
print("got", value)
making 1
got 1
making 2
got 2
making 3
got 3
At yield, the value rides out to the loop and the function pauses right there, like a bookmark. When the loop asks again, it wakes up on the next line. "making" and "got" take turns, so values never pile up. return ends a function for good; yield only pauses it and keeps its variables. Calling count_up(2) runs none of its code: it gives back a generator, each next() runs it to the next yield, and running off the end raises StopIteration, which a for loop catches quietly.
A pipeline of generators
LINES = [
"1,INFO,start",
"2,ERROR,disk full",
"3,INFO,ok",
"4,ERROR,timeout",
"5,INFO,done",
]
with open("small.log", "w", newline="\n") as f:
f.write("\n".join(LINES) + "\n")
def read_lines(name):
print("open")
with open(name) as f:
for line in f:
yield line.strip()
def only(lines, word):
for line in lines:
if word in line:
yield line
def split_fields(lines):
for line in lines:
yield line.split(",")
lines = read_lines("small.log")
errors = only(lines, "ERROR")
fields = split_fields(errors)
print("built")
for row in fields:
print(row)
built
open
['2', 'ERROR', 'disk full']
['4', 'ERROR', 'timeout']
"built" prints before "open": building a pipeline does no work, and the file isn't even open yet. The for loop asks fields for a row, which asks errors, which asks lines, and now the file opens. INFO lines stop at only; ERROR lines ride all the way through. The lesson measured the memory with tracemalloc on a 200,000-line file: both ways count the same lines, and one line at a time peaks at less than a twentieth of readlines().
Settings files with tomllib
import tomllib
TEXT = """\
[project]
name = "orders-tool"
version = "1.2"
[tool.orders]
debug = true
retries = 3
hosts = ["alpha", "beta"]
"""
with open("pyproject.toml", "w", newline="\n") as f:
f.write(TEXT)
with open("pyproject.toml", "rb") as f:
config = tomllib.load(f)
orders = config["tool"]["orders"]
print(config["project"]["name"])
print(orders["retries"] + 1)
print(orders["debug"])
print(orders["hosts"])
orders-tool
4
True
['alpha', 'beta']
You've seen pyproject.toml in uv and pyproject.toml. tomllib comes with Python, wants binary mode, and gives you nested dictionaries. Unlike CSV, retries is already a number, debug is already True and hosts is already a list. It only reads, which is usually all a program needs.
pickle, and why you never unpickle what you don't trust
pickle.dump(data, f) with wb saves Python objects as they are, and pickle.load with rb brings them back equal to the original. That's handy for things that take a long time to build, like a trained model. But a class can tell pickle what to run when it's loaded:
import pickle
class Sneaky:
def __reduce__(self):
return (print, ("code ran while loading",))
blob = pickle.dumps(Sneaky())
print("loading...")
pickle.loads(blob)
loading...
code ran while loading
We never called print ourselves. The code inside those bytes ran on load, and it could have been anything on your machine. Use pickle only for files you made yourself. For anything from outside, use JSON, because loading JSON only gives you data.
Quick recap
| Need | Use |
|---|---|
| Flat table | csv.DictReader / DictWriter, values are strings |
| Nested data | json.dumps/loads (strings), dump/load (files) |
| Unknown types in JSON | default= function or a JSONEncoder |
| Huge text file | for line in f |
| Huge binary file | f.read(8192) in a loop |
| Your own lazy steps | generators with yield |
| Settings | tomllib.load |
| Your own Python objects | pickle, trusted files only |
Try it yourself
Take this orders.csv and use generators to filter it into a JSON file, keeping only orders worth 20 or more and skipping rows with a bad quantity:
item,qty,price
pen,10,1.5
book,2,12.0
lamp,1,30.0
cup,x,4.0
desk,1,150.0
One solution, reading the JSON back, prints:
book 24.0
lamp 30.0
desk 150.0Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Set Up a Python AI Project with uv, VS Code and an API Key in .env
One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.
uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
One tool instead of venv, activate, pip install and pip freeze. Build a small chatbot project with uv init, hit ModuleNotFoundError, fix it with uv add, read pyproject.toml and uv.lock, then delete .venv and rebuild it with uv sync.
Python try and except Basics: Catch an Error and Keep Going
An exception is the object Python creates when something goes wrong. Catch it with try and a named except, read it with as, add else and finally, retry bad input in a loop, and see why a bare except hides your bugs.
Read and Write a File in Python: open, with, Modes and Encoding
Make your data outlive the program: write notes.txt with open and with, read it back three ways, see how w wipes a file and a appends, why encoding matters, and what to do when a file isn't there.
