Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Modules, Files and Errors

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Modules, Files and Errors

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']
A generator pipeline: read_lines yields one line, only keeps lines with ERROR, split_fields turns each into a list, and the for loop pulls one item at a time through the chain read_lines one line only "ERROR" INFO stops here split_fields line → list for row print(row) the loop's "next, please" runs back up the chain one line on the belt at a time, so memory stays flat
Building the pipeline does no work. The for loop pulls each line through, one at a time.

"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

NeedUse
Flat tablecsv.DictReader / DictWriter, values are strings
Nested datajson.dumps/loads (strings), dump/load (files)
Unknown types in JSONdefault= function or a JSONEncoder
Huge text filefor line in f
Huge binary filef.read(8192) in a loop
Your own lazy stepsgenerators with yield
Settingstomllib.load
Your own Python objectspickle, 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.0

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 32 of 48

Previous
Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
Next post
Python Practice: Build a Log File Analyzer and a File Organizer

Related 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.

On this page

  • Reading CSV
  • DictReader: ask by name
  • Writing CSV
  • JSON: dumps and loads
  • Types JSON doesn't know
  • Your own objects
  • Files too big for memory
  • yield: build your own line-at-a-time functions
  • A pipeline of generators
  • Settings files with tomllib
  • pickle, and why you never unpickle what you don't trust
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related 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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.