Sub topic 9
Converting CSV strings to numbers, booleans, and dates
This chapter assumes you can open files with with, write functions, handle exceptions, and read a CSV file with csv.DictReader. If not, review those topics first.
Why every CSV value is a string
CSV has no types. The csv module reads 42, true, and 2026-11-26 as the strings "42", "true", and "2026-11-26". Python will not guess. Doing arithmetic on the raw values gives wrong results or errors: "3" * 2 is "33", and "3" + 1 raises TypeError.
You have to convert each field yourself. The usual approach is one small function per type, applied in a single place right after reading.
Numbers
Use int() and float(). Both raise ValueError when the text is not a valid number, and both accept surrounding whitespace.
print(int("42"), float("3.5"), int(" 7 "))
try:
int("3.5")
except ValueError as e:
print(e) # invalid literal for int() with base 10: '3.5'int("3.5") fails. If a column may hold decimals, use float(). For money, prefer decimal.Decimal to avoid binary rounding errors.
Empty fields
An empty field arrives as "", and int("") raises ValueError. Decide what a missing value means for your data. Often None is the right answer.
def to_int(text):
text = text.strip()
return int(text) if text else None
print(to_int("12"), to_int("")) # 12 NoneBooleans
Do not use bool("false"). Any non-empty string is truthy, so bool("false") is True. Compare against the spellings your data uses.
TRUE_VALUES = {"true", "yes", "1", "y"}
FALSE_VALUES = {"false", "no", "0", "n"}
def to_bool(text):
value = text.strip().lower()
if value in TRUE_VALUES:
return True
if value in FALSE_VALUES:
return False
raise ValueError(f"Not a boolean: {text!r}")
print(to_bool("Yes"), to_bool("0")) # True FalseRaising on unknown values is deliberate. Silently treating "ture" as False hides data errors.
Dates
Use datetime.strptime with a format string, or date.fromisoformat for ISO 8601 text (YYYY-MM-DD).
from datetime import date, datetime
print(date.fromisoformat("2026-11-26"))
print(datetime.strptime("26/11/2026", "%d/%m/%Y").date())Both raise ValueError for impossible dates such as 2026-02-30. Be explicit about day/month order. 03/04/2026 means different things in different countries, so match the format string to the source.
Converting a whole row
Keep the conversions in one table that maps column names to functions. This makes the schema visible and easy to change.
import csv
from datetime import date
CONVERTERS = {
"name": str,
"qty": int,
"price": float,
"in_stock": lambda t: t.strip().lower() in {"true", "yes", "1"},
"added": date.fromisoformat,
}
def convert_row(row):
return {key: CONVERTERS[key](value) for key, value in row.items()}
text = "name,qty,price,in_stock,added\napple,3,0.5,yes,2026-11-26\npear,5,0.75,no,2026-11-20\n"
rows = [convert_row(r) for r in csv.DictReader(text.splitlines())]
print(rows[0])
print(sum(r["qty"] * r["price"] for r in rows))csv.DictReader accepts any iterable of lines, so a list of strings works the same as an open file.
Reporting bad rows
A single bad value should not hide which row caused it. Catch ValueError, include the row number, and decide whether to stop or skip.
import csv
def load(lines):
good, errors = [], []
reader = csv.DictReader(lines)
for number, row in enumerate(reader, start=2): # line 1 is the header
try:
good.append({"name": row["name"], "qty": int(row["qty"])})
except (ValueError, KeyError) as e:
errors.append((number, str(e)))
return good, errors
good, errors = load(["name,qty", "apple,3", "pear,many"])
print(good) # [{'name': 'apple', 'qty': 3}]
print(errors) # [(3, "invalid literal for int() with base 10: 'many'")]Common mistakes:
- Converting inside every place the data is used, instead of once after reading.
- Using
bool()on text. - Forgetting that missing trailing fields give
NoneinDictReader, which makes.strip()fail withAttributeError. - Assuming a date format without checking the source.
Exercise
Why does bool("false") return True, and what should you do instead when a CSV column holds the words "true" and "false"?
Show answer
bool() on a string only checks whether it is empty, and "false" is not empty, so it is truthy. Instead, lowercase and strip the text and compare it against known true and false spellings, raising ValueError for anything else.
Exercise
A qty column contains "4", "", and "2.5". Which of these fail with int(), and how would you handle each?
Show answer
"" and "2.5" fail with ValueError. Treat the empty string as missing and return None. For "2.5", decide whether quantities may be fractional: if so use float(), and if not, report the row as invalid.