Sub topic 11
Reading and Writing CSV and JSON
This chapter assumes you can already open files with open(), use the with statement, and set an explicit encoding. It also assumes you know the difference between str and bytes, and that you can write a try/except block. The goal is to move structured data between Python objects and text files using the standard library's csv and json modules.
Two formats, two shapes of data
Both formats are plain text files, so everything you learned about modes, encodings, and newlines still applies. The difference is the kind of data they hold.
| Aspect | CSV | JSON |
|---|---|---|
| Shape | Flat table of rows and columns | Nested objects, lists, and scalars |
| Types on read | Every value is a `str` | `str`, `int`, `float`, `bool`, `None`, `list`, `dict` |
| Typical use | Spreadsheets, exports, logs | Configuration, APIs, saved program state |
| Module | `csv` | `json` |
| Streaming | Natural, one row at a time | Whole document by default |
Writing CSV
A CSV file stores one record per line, with fields separated by commas. Quoting rules handle fields that contain commas, quotes, or line breaks. Do not build these lines yourself with ",".join(...). A name like Smith, Jane would break the row. Use the csv module.
import csv
import json
rows = [{"name": "Ada", "age": 36}, {"name": "Linus", "age": 28}]
with open("people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows(rows)
with open("people.json", "w", encoding="utf-8") as f:
json.dump(rows, f, indent=2)
with open("people.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded)This writes the same records in both formats and reads the JSON back. The last line prints [{'name': 'Ada', 'age': 36}, {'name': 'Linus', 'age': 28}].
DictWriter needs fieldnames because dictionaries have no fixed column order for the file. writeheader() writes that list as the first line. writerows() accepts any iterable of dictionaries, so a generator works too.
Why `newline=""`
The csv module writes its own line terminator (\r\n by default) and handles line breaks inside quoted fields itself. If the file object also translates newlines, you can end up with \r\r\n on Windows, or with embedded newlines corrupted on read. Passing newline="" turns off the file's translation so the csv module sees the raw characters. Use it for both reading and writing.
Plain writers and extra options
When your rows are lists or tuples, use csv.writer. It has no header logic, so you write the header as an ordinary row.
import csv
with open("scores.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["player", "note"])
writer.writerow(["Mia", 'said "hello", then left'])
writer.writerow(["Ravi", "line one\nline two"])The second and third rows contain quotes, a comma, and a newline. The writer wraps those fields in double quotes and doubles the inner quotes, so the file stays valid.
Both writer types accept a delimiter argument, such as delimiter="\t" for tab-separated files or delimiter=";" for the semicolon-separated files some European spreadsheet settings produce. The quoting argument controls when fields are quoted. The default, csv.QUOTE_MINIMAL, quotes only when needed. csv.QUOTE_ALL quotes every field.
Values that are not strings are converted with str(), and None becomes an empty field. If a dictionary has a key that is not in fieldnames, DictWriter raises ValueError. Pass extrasaction="ignore" to skip extra keys instead. A key that is missing from a row gets the restval value, which is an empty string by default.
Reading CSV
DictReader uses the first line as column names and yields one dictionary per row.
import csv
with open("people.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], int(row["age"]) + 1)This prints Ada 37 and then Linus 29. The reader consumes the file lazily, so a very large CSV uses little memory as long as you process each row and move on, instead of collecting every row into a list.
Use csv.reader when the file has no header or you prefer positions. It yields a list of strings per row. DictReader also accepts a fieldnames argument for headerless files. If a row has more fields than names, the extras are collected under the key given by restkey, which is None by default. A short row gets None for the missing columns.
Files exported from Excel sometimes begin with a byte order mark. If your first column name looks like '\ufeffname', open the file with encoding="utf-8-sig", which strips the mark on read. For writing a file that Excel must open with the right accents, utf-8-sig also works, since it writes the mark.
Writing JSON
JSON is a text format for nested data. json.dump(obj, file) writes to an open file. json.dumps(obj) returns a string, which is useful for logging, network messages, or building the text before an atomic write.
import json
data = {"city": "Z\u00fcrich", "point": (1, 2), "tags": ["a", "b"]}
print(json.dumps(data))
print(json.dumps(data, ensure_ascii=False))
print(json.dumps(data, indent=2, sort_keys=True))The first call prints {"city": "Z\u00fcrich", "point": [1, 2], "tags": ["a", "b"]}. By default ensure_ascii=True escapes every non-ASCII character, which is safe in any encoding but hard to read. With ensure_ascii=False the output keeps Zürich, so open the file with encoding="utf-8" when you write it. The indent argument makes the file readable and diff-friendly. sort_keys=True makes the output order stable.
The mapping between Python and JSON is not perfectly reversible.
| Python value | JSON text | Comes back as |
|---|---|---|
| `tuple` | array | `list` |
| `dict` with `int` keys | object with string keys | `dict` with `str` keys |
| `None` | `null` | `None` |
| `float("nan")` | `NaN` (not valid standard JSON) | `float` nan |
| `set`, `datetime`, `Path` | not supported | `TypeError` on write |
Custom types with `default`
For types JSON does not know, pass a default function. It is called only for objects the encoder cannot handle, and it must return a serializable value or raise TypeError.
import json
from datetime import date
def encode(obj):
if isinstance(obj, date):
return obj.isoformat()
raise TypeError(f"Cannot serialize {type(obj).__name__}")
print(json.dumps({"when": date(2026, 11, 26)}, default=encode))This prints {"when": "2026-11-26"}. Reading it back gives you a string. Converting it to a date again is your job, for example with date.fromisoformat().
Reading JSON
json.load(file) parses a whole file. json.loads(text) parses a string. A malformed document raises json.JSONDecodeError, which is a subclass of ValueError and carries the line and column of the problem.
import json
try:
with open("settings.json", encoding="utf-8") as f:
settings = json.load(f)
except FileNotFoundError:
settings = {}
except json.JSONDecodeError as err:
print(f"settings.json is not valid JSON: line {err.lineno}, column {err.colno}")
settings = {}The order of the except clauses is not important here, because the two exception types are unrelated. Catching both lets a program start with defaults when the file is absent or damaged.
A JSON file holds exactly one top-level value. You cannot append a second object to the file with json.dump and expect json.load to read it. It will fail with Extra data.
Large data: JSON Lines
json.load reads the entire document into memory. For a log of events that grows over time, use JSON Lines, also called NDJSON. Each line of the file is one complete JSON document. Appending is a single write, and reading is a line-by-line loop.
import json
events = [{"id": 1, "type": "start"}, {"id": 2, "type": "stop"}]
with open("events.jsonl", "a", encoding="utf-8") as f:
for event in events:
f.write(json.dumps(event, ensure_ascii=False) + "\n")
with open("events.jsonl", encoding="utf-8") as f:
for line in f:
if line.strip():
event = json.loads(line)
print(event["id"], event["type"])Do not pass indent here. Indented output spans several lines and breaks the one-document-per-line rule. The json.dumps call escapes any newline inside a string value as \n, so a raw line break never appears inside a record.
Choosing between them
- Pick CSV when the data is a flat table and people or spreadsheets will open the file. Accept that you must convert types yourself.
- Pick JSON when records contain lists, nested objects, or mixed types, or when another program consumes the file.
- Pick JSON Lines when the file grows by appending or is too big to load at once.
- Whichever you choose, write the file with an explicit encoding. For files that matter, combine this chapter with the temporary-file pattern from the safe-writes chapter, using
json.dumpsto produce the text and then writing it atomically.
Common mistakes
- Opening a CSV file without
newline="". - Treating CSV values as numbers without converting them.
- Building CSV lines with string formatting, which breaks on commas and quotes in the data.
- Calling
json.dumptwice on the same file and then trying tojson.loadit. - Expecting a tuple, a set, or an integer dictionary key to survive a JSON round trip unchanged.
- Forgetting that
json.dumpraisesTypeErrormidway through, which can leave a partly written file. Build the string withjson.dumpsfirst, then write it.
Exercise
A file orders.csv has the header item,qty,price and several rows. Describe how you would write a function that reads it and saves orders.json as a list of dictionaries in which qty is an int and price is a float. Which three arguments or calls matter for correctness when opening the CSV file and writing the JSON file?
Show answer
Open the CSV with open("orders.csv", newline="", encoding="utf-8") and loop over csv.DictReader(f). For each row, build a new dictionary that keeps item as a string and converts row["qty"] with int() and row["price"] with float(), because the csv module returns only strings. Collect the dictionaries in a list. Then open orders.json for writing with encoding="utf-8" and call json.dump(records, f, indent=2). The three details that matter are newline="" on the CSV file, the explicit encoding on both files, and the manual type conversion after reading.
Exercise
You run json.dumps({1: "a", 2: ("b", "c")}) and then pass the result to json.loads. What does the loaded dictionary look like, and why?
Show answer
It is {'1': 'a', '2': ['b', 'c']}. JSON object keys must be strings, so the integer keys become "1" and "2". JSON has no tuple type, so the tuple is written as an array and read back as a list.