Sub topic 9
Converting CSV strings to numbers, booleans, and dates
The csv module reads every field as text. This chapter shows how to convert those strings into int, float, Decimal, bool, date, and datetime values, how to handle blank fields, and how to report bad rows without stopping the whole run.
This chapter assumes you can use csv.DictReader (covered in the previous chapter), write small functions, and catch exceptions. You should also know how to open files with newline="" and an explicit encoding.
Why every field is a string
CSV has no types. A file stores characters, and the csv module splits them into fields without guessing what they mean. The reader gives you "3", never 3.
import csv
import io
data = "name,qty,price\napple,3,1.25\n"
for row in csv.DictReader(io.StringIO(data)):
print(row)
print(row["qty"] + row["qty"])
print(row["qty"] * 2)This prints:
{'name': 'apple', 'qty': '3', 'price': '1.25'}
33
33Adding two strings joins them, so "3" + "3" is "33". No error is raised, which makes this a quiet bug. It is the main reason to convert early, right after reading each row, so that the rest of your program works with real types.
The module has a QUOTE_NONNUMERIC option on the reader that converts unquoted fields to float. It converts everything unquoted, including text fields, and it fails on any non-numeric unquoted field. It is rarely the right tool. Explicit per-column conversion, shown below, is clearer.
Numbers
Integers and floats
int() and float() accept a string and raise ValueError if it is not a valid number. Both ignore surrounding whitespace.
print(int(" 42 "))
print(float("1.5e3"))
for text in ["3.0", "1,000", "", "12abc"]:
try:
int(text)
except ValueError as exc:
print(repr(text), "->", exc)int("3.0") fails even though the value is whole. If a column may contain "3.0", which spreadsheet exports often produce, decide on a rule. One option is int(float(text)). That silently truncates "3.7" to 3, so check float(text).is_integer() first if truncation would be a bug.
Thousands separators such as "1,000" and locale decimal commas such as "1,25" are not parsed. Clean or normalize those fields yourself, and only when you know which locale the file uses.
Floats accept surprising text
float() accepts "nan", "inf", and "-infinity" in any letter case. A column of prices that contains NaN will convert without error, and every comparison with it is False. If those values are not meaningful in your data, reject them:
import math
def parse_finite_float(text):
value = float(text)
if not math.isfinite(value):
raise ValueError(f"not a finite number: {text!r}")
return valueMoney needs Decimal
Binary floats cannot represent most decimal fractions exactly. For currency and anything else that must add up cleanly, use decimal.Decimal, and pass it the string, not a float.
from decimal import Decimal
print(0.1 + 0.2)
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))This prints 0.30000000000000004 and then True. Because CSV already gives you strings, Decimal(text) is the natural conversion.
Booleans
The most common mistake is bool(text). Any non-empty string is truthy, including "False" and "0".
print(bool("False"))
print(bool("0"))
print(bool(""))This prints True, True, False. Instead, compare against the set of spellings your data uses, and raise an error on anything else. Failing on an unknown value is better than guessing.
TRUE_VALUES = {"true", "t", "yes", "y", "1"}
FALSE_VALUES = {"false", "f", "no", "n", "0"}
def parse_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(parse_bool("Yes"), parse_bool(" FALSE "))This prints True False. Keep the two sets short and agree on them with whoever produces the file. A blank field is neither true nor false. Handle blanks before calling parse_bool, as described in the section on missing values.
Dates and datetimes
For ISO 8601 text, use the fromisoformat methods on date and datetime. For any other layout, use datetime.strptime with a format string.
from datetime import date, datetime
print(date.fromisoformat("2026-11-26"))
print(datetime.fromisoformat("2026-11-26T10:50:00"))
print(datetime.strptime("26/11/2026", "%d/%m/%Y").date())The output is:
2026-11-26
2026-11-26 10:50:00
2026-11-26Three details matter:
strptimereturns adatetimeeven for date-only input. Call.date()if you want adate.- Before Python 3.11,
fromisoformataccepted only the exact format thatisoformat()produces. Python 3.11 and later accept most ISO 8601 variants, such as20261126and a trailingZ. If your code must run on older versions, usestrptimewith an explicit format. - A format like
%d/%m/%Yversus%m/%d/%Yis ambiguous.03/04/2026parses successfully under both and gives different dates. Confirm the convention with the data source rather than assuming.
Timezones are the other trap. A plain datetime is naive, meaning it has no timezone. If the file mixes offsets (+01:00) or you compare against aware datetimes, naive and aware values raise TypeError when compared. Decide on one convention, usually UTC, and normalize on read.
Missing values
A blank field arrives as "", and int("") raises ValueError. Python has no standard CSV rule for missing data, so choose a representation. None is the usual choice because it is distinct from every valid value, including 0 and False.
A small wrapper keeps that rule in one place:
def optional(parser):
def wrapper(text):
text = text.strip()
if text == "":
return None
return parser(text)
return wrapper
parse_int = optional(int)
print(parse_int("7"), parse_int(" "))This prints 7 None. Some files use sentinel strings such as NA, N/A, or - instead of blanks. Extend the check to a set, for example if text in {"", "NA", "N/A"}, and keep the set visible in one place.
A schema-driven converter
Converting columns one at a time inside a loop gets repetitive. Instead, describe the file as a mapping from column name to parser function, then apply it to every row. The next program reads a small file, converts each row, and separates valid rows from bad ones with line numbers.
import csv
import io
from datetime import date
from decimal import Decimal, InvalidOperation
TRUE_VALUES = {"true", "t", "yes", "y", "1"}
FALSE_VALUES = {"false", "f", "no", "n", "0"}
def parse_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}")
def optional(parser):
def wrapper(text):
text = text.strip()
if text == "":
return None
return parser(text)
return wrapper
SCHEMA = {
"name": str.strip,
"qty": optional(int),
"price": optional(Decimal),
"in_stock": parse_bool,
"added": optional(date.fromisoformat),
}
def convert_row(row, schema):
converted = {}
for column, parser in schema.items():
raw = row[column]
if raw is None:
raise ValueError(f"column {column!r}: value missing (short row)")
try:
converted[column] = parser(raw)
except (ValueError, InvalidOperation) as exc:
raise ValueError(f"column {column!r}: {raw!r} ({exc})") from exc
return converted
def read_typed(file, schema):
reader = csv.DictReader(file)
missing = set(schema) - set(reader.fieldnames or [])
if missing:
raise ValueError(f"missing columns: {sorted(missing)}")
good, bad = [], []
for row in reader:
try:
good.append(convert_row(row, schema))
except ValueError as exc:
bad.append((reader.line_num, str(exc)))
return good, bad
text = """name,qty,price,in_stock,added
apple,3,1.25,yes,2026-11-01
pear,,0.80,no,2026-11-02
plum,x,2.00,true,2026-11-03
fig,5,3.10,maybe,26/11/2026
"""
good, bad = read_typed(io.StringIO(text), SCHEMA)
for row in good:
print(row)
for line, message in bad:
print("line", line, "->", message)The output is:
{'name': 'apple', 'qty': 3, 'price': Decimal('1.25'), 'in_stock': True, 'added': datetime.date(2026, 11, 1)}
{'name': 'pear', 'qty': None, 'price': Decimal('0.80'), 'in_stock': False, 'added': datetime.date(2026, 11, 2)}
line 4 -> column 'qty': 'x' (invalid literal for int() with base 10: 'x')
line 5 -> column 'in_stock': 'maybe' (not a boolean: 'maybe')Several design choices here are worth keeping:
- The column check happens once, before any row is read. A misspelled header fails immediately with a clear message instead of raising
KeyErroron every row. reader.line_numis the physical line in the file, so it stays correct even when a quoted field spans several lines. Counting rows yourself does not.- A short row makes
DictReaderfill the missing columns withNone, soconvert_rowchecks forNonebefore calling a parser. raise ... from exckeeps the original exception attached for debugging.- Each bad row is collected, not raised, so one bad value does not hide the others. For a strict pipeline, raise on the first error instead. Pick the behavior deliberately.
Writing typed values back to CSV
csv.writer calls str() on each non-string value, so most types round-trip without work. Two cases need attention: None is written as an empty field, and True is written as True.
import csv
import io
from datetime import date
buffer = io.StringIO()
csv.writer(buffer).writerow([None, True, 1.5, date(2026, 11, 26)])
print(repr(buffer.getvalue()))This prints ',True,1.5,2026-11-26\r\n'. The \r\n line ending is the writer's default. It reads back correctly with parse_bool, because "true" is in TRUE_VALUES, and with date.fromisoformat. If another program consumes the file, format the values yourself, for example "yes" if flag else "no" or d.strftime("%d/%m/%Y"), so that it matches what that program expects.
Common failures
| Symptom | Cause | Fix |
|---|---|---|
| `"3" + "3"` gives `"33"` | The value was never converted | Convert each row right after reading it |
| `bool("False")` is `True` | Any non-empty string is truthy | Use a lookup like `parse_bool` |
| `ValueError` on `int("3.0")` | `int` rejects decimal text | Parse with `float` and check `is_integer()` |
| `except ValueError` misses a bad price | `Decimal` raises `InvalidOperation` | Catch both exception types |
| `NaN` appears in a numeric column | `float` accepts `"nan"` | Check with `math.isfinite` |
| `KeyError: 'name'` on the first row | A BOM is part of the first header | Open with `utf-8-sig` |
| `AttributeError` on `None` | A short row left a column as `None` | Check for `None` before parsing |
Exercise
A file has a column active with values Y, N, and sometimes a blank. Write a parser that returns True for Y, False for N, None for a blank, and raises ValueError for anything else. Which functions from this chapter can you reuse?
Show answer
Reuse optional and parse_bool, because parse_bool already accepts y and n in any letter case. The parser is parse_active = optional(parse_bool). A blank (or whitespace-only) value returns None before parse_bool runs, "Y" returns True, "N" returns False, and a value like "maybe" raises ValueError. Note that parse_bool would also accept "1" or "true". If only Y and N are allowed, write a stricter parser with just those two values.
Exercise
A CSV column amount holds "19.99", "abc", and "". You convert with try: Decimal(text) except ValueError. What goes wrong, and how do you fix it?
Show answer
Decimal("") and Decimal("abc") raise decimal.InvalidOperation, which is not a ValueError, so the except clause does not catch it and the program crashes. Fix it by catching (ValueError, InvalidOperation), importing InvalidOperation from decimal, and by handling the blank field first, for example with optional(Decimal), so that "" becomes None instead of an error.