Sub topic 3
Converting CSV Strings to Numbers, Booleans, and Dates
This chapter assumes you know basic Python syntax, dictionaries, lists, strings, functions, exceptions, and the with statement for opening files.
Convert CSV values explicitly
The csv module returns every field as a string. Convert each value at the point where you read it. Do not rely on later code to guess its type.
import csv
from datetime import date
def parse_bool(value):
return value.strip().lower() in {"true", "yes", "1"}
def parse_date(value):
return date.fromisoformat(value)
with open("orders.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
order = {
"name": row["name"],
"quantity": int(row["quantity"]),
"price": float(row["price"]),
"paid": parse_bool(row["paid"]),
"ordered": parse_date(row["ordered"]),
}
print(order)Be careful with empty strings, invalid numbers, and unexpected boolean values. A parser should either validate these cases or raise a useful error.
Delimiters and quoting
CSV is a family of related formats. A file may use commas, semicolons, or tabs as delimiters. Fields containing the delimiter are normally quoted.
import csv
with open("items.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f, delimiter=";", quoting=csv.QUOTE_ALL)
writer.writerow(["name", "note"])
writer.writerow(["pear", "large; ripe"])Using newline="" prevents extra blank lines on some platforms. Explicit UTF-8 encoding makes text handling predictable.
Convert between CSV and JSON
A CSV-to-JSON conversion should also convert types. Otherwise, quantities remain JSON strings.
import csv
import json
with open("items.csv", newline="", encoding="utf-8") as f:
items = [
{"name": row["name"], "qty": int(row["qty"])}
for row in csv.DictReader(f)
]
with open("items.json", "w", encoding="utf-8") as f:
json.dump(items, f, indent=2)JSON objects map naturally to DictReader or DictWriter, but nested JSON objects and lists need a separate design because CSV has flat rows.
Process large files incrementally
For large CSV files, iterate over DictReader instead of building a list. JSON Lines stores one JSON value per line, allowing the same pattern.
import json
with open("events.jsonl", encoding="utf-8") as f:
for line in f:
event = json.loads(line)
if event["type"] == "login":
print(event["id"])Exercise
Why does int(row["qty"]) matter when converting CSV to JSON?
Show answer
CSV readers return strings, so conversion makes qty a JSON number rather than a JSON string.