18.1 Files, CSV, and JSON
Read and write structured data with explicit encoding.
Before you start
Work through the earlier fundamentals chapters. Use a Python 3 interpreter and run each example locally.
Core concepts
Use pathlib.Path for filesystem paths and with to close open files even when an error occurs. Specify UTF-8 when reading and writing text. Writing with mode w replaces an existing file; choose output paths deliberately.
Use csv.DictReader for header-based CSV records rather than splitting on commas: quoted fields may contain commas. CSV values are strings, so validate and convert fields. JSON supports nested objects and arrays; decoding untrusted or malformed input can fail.
Worked example
import csv
from io import StringIO
sample = "name,status\nweb-01,healthy\nweb-02,critical\n"
for row in csv.DictReader(StringIO(sample)):
if row["status"] == "critical":
print(row["name"])
Mini lab
Parse the sample CSV and serialize critical rows as JSON. Expected: [{"name": "web-02", "status": "critical"}]. Then try input with a header but no rows.
Hint
Start with the smallest input. Print intermediate values while exploring, then replace those prints with checks of the expected result.Show a solution
import csv
import json
from io import StringIO
sample = "name,status\nweb-01,healthy\nweb-02,critical\n"
rows = [row for row in csv.DictReader(StringIO(sample))
if row["status"] == "critical"]
print(json.dumps(rows))
Knowledge check
Why not parse CSV with line.split(",")?
Check your answer
A quoted field may contain commas or newlines; a CSV parser handles the format correctly.Common mistake
Validate required headers before processing records. Never overwrite the input file while you are reading it.
Completion checklist
- Run the example and explain its output.
- Complete the mini lab without copying the solution.
- Test an edge case and explain how the code handles it.
- Answer the knowledge check in your own words.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form