Sub topic 11
Reading and Writing CSV and JSON
This chapter assumes you can open files with with open(...), set an explicit encoding, and handle basic exceptions. CSV and JSON are the two text formats you will meet most often. Python's standard library reads and writes both, so you need no extra packages.
Why use a parser instead of string methods
Splitting a line on commas breaks as soon as a value contains a comma, a quote, or a newline. The csv module follows the quoting rules for you. The json module does the same for nested data. In both cases the module sits between your Python objects and the text in the file.
Writing CSV and JSON
The example below writes the same records in both formats, then reads the JSON back.
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)Three details matter here:
newline=""is required when you open a file for thecsvmodule. The module writes its own line endings. Without this argument, Windows can end up with blank lines between rows.DictWritermaps dictionary keys to columns usingfieldnames.writeheader()writes the column names as the first line.json.dump(obj, f)writes to a file object.indent=2makes the output readable. Leave it out for compact output.
Reading CSV
csv.DictReader uses the header row as dictionary keys. Open the file with newline="" here as well.
import csv
with open("people.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["name"], int(row["age"]))The csv module returns every value as a string. The age 36 comes back as "36", so convert it yourself with int() or float(). JSON is different: it keeps numbers, booleans, null, lists, and objects, and maps them to int/float, bool, None, list, and dict.
| Feature | CSV | JSON |
|---|---|---|
| Shape | Flat rows and columns | Nested objects and lists |
| Value types | Strings only | Strings, numbers, booleans, null |
| Read whole file | Not required, iterate row by row | Required, `json.load` parses it all |
| Typical use | Tables, spreadsheet export | Configuration, API data |
Common errors
- A blank line after every row on Windows. You forgot
newline=""when opening the CSV file. TypeError: Object of type X is not JSON serializable. JSON supports only basic types. Convert objects such asdatetimeorsetfirst, for example withisoformat()orlist().json.JSONDecodeError. The file is empty, truncated, or not valid JSON. Catchjson.JSONDecodeErrorwhen the input comes from outside your program.- Garbled non-ASCII text. Pass the same
encodingwhen you write and when you read. By defaultjson.dumpescapes non-ASCII characters as\uXXXX. Addensure_ascii=Falseto write them as they are. - Wrong types after reading CSV. Every field is a string until you convert it.
Exercises
Exercise
You open a CSV file for writing with open("out.csv", "w", encoding="utf-8") and use csv.writer. On Windows the output has a blank line after each row. What is the fix, and why does it work?
Show answer
Add newline="" to open(). The csv module writes its own row terminators. Without newline="", Python's text layer also translates \n into \r\n, which produces doubled line endings and the blank lines.
Exercise
A CSV file has a column age. After reading it with csv.DictReader, row["age"] + 1 raises a TypeError. Why, and how do you fix it?
Show answer
The csv module returns every value as a string, so "36" + 1 fails. Convert first with int(row["age"]) + 1.