CSV is a delimited text format for rows and columns, with quoting rules for values that contain separators or line breaks.
Read fields by name, select the correct dialect and preserve quoted text before converting values to application types.
A comma inside a quoted city name is data; a comma between fields is structure. Splitting on every comma cannot tell the difference. Begin with one broken row, let the CSV reader preserve its fields, then decide whether the resulting row satisfies the table your application expects.
You'll build read_csv(text), the first piece of Quarry's vault: it reads the
exports people actually send, not the ones you wish they sent.

Import a support-ticket export with a quoted city
A support team's export has one row per ticket. Someone typed a city with its state after a comma, so the tool that wrote the file quoted that field — exactly what quoting is for:
line = '3,"Pune, MH",95'
print(len(line.split(",")))Four fields where there should be three, and nothing raised an error. The
ms column now holds ' MH"'. A shifted column is worse than a crash — the
program carries on and stores the wrong number under the right heading. Real
exports also allow a doubled quote inside a quoted field ("she said ""hi"""),
a newline inside a quoted field, \r\n line endings, and a byte-order mark
glued to the first header. Each one breaks split differently; the embedded
newline breaks it before you even reach the commas, because splitting on \n
has already cut the record in half.
csv.reader reads this correctly, and it wants an iterable of lines, not one
string — a file, a list, or io.StringIO, which wraps a string so it behaves
like one:
Fix the version that still uses split, so every city comes out whole:
Run it first and look at the second city. Then replace the split with a csv.reader so the quoted comma stays inside its field.
Preparing this topic’s interactive investigation…
Pull a column by name from a reshuffled export
Column positions are fragile — insert a column and row[2] silently means
something else. csv.DictReader reads the first row as the header and hands
you each later row as a dict, keyed by name:
Notice the blank line before 3,Oslo,40 — DictReader skips fully empty
rows, which is what you want from a hand-edited file. Every value is still a
str, which is easy to forget:
import csv, io
rows = list(csv.DictReader(io.StringIO("item,qty\nbolt,3\n")))
print(rows[0]["qty"] * 2)Step through a small reader loop and watch row become a dict each pass,
while the running total only changes once the string is converted:
Read a spreadsheet from Germany
Much of Europe writes decimals with a comma, so spreadsheets there separate
fields with ; instead. Log exporters favour tabs or |. The csv module
calls one set of these choices a dialect; delimiter is the one you'll
touch most:
How do you know which delimiter a file uses before reading it? csv.Sniffer
guesses from a sample, but it can guess wrong on short or odd samples. Quarry
uses a simpler rule: look at the header line and pick the candidate that
appears most often in it. Headers rarely contain punctuation, so the
delimiter is almost always the most common character:
On a tie, max returns the first candidate, so a one-column file falls back
to the comma — a reasonable default.
Traps worth knowing
Writing has the mirror-image bug. Building rows with ",".join(values)
breaks the moment a value contains a comma. csv.DictWriter quotes only the
fields that need it, and its line ending surprises almost everyone:
import csv, io
buf = io.StringIO()
csv.writer(buf).writerow(["a", "b"])
print(repr(buf.getvalue()))A leading BOM breaks row["id"] on a file that looks perfect in any
editor. Strip it first: text.removeprefix(""). Then the header reads
id, not 'id'.
A parsed row can still violate the table contract
A CSV reader handles quoting; it does not establish that each row has the columns your application needs. Consider a header id,ms followed by 7,120,extra. DictReader stores the surplus field under a None key. A short row such as 8 gives ms the value None. These are structural observations to validate before calling int.
Read the third row carefully: "0" is present text, not a missing cell. Distinguish missing column, empty cell, invalid number, and valid zero; a single if not value after numeric conversion erases that distinction. Duplicate header names also need a policy, because a dict cannot keep two values under the same key.
The delimiter counter in this lesson is a deliberately small rule for the supplied exports. Quoted punctuation in a header can defeat it. Prefer an agreed dialect; when sniffing is necessary, treat it as a hypothesis and validate the resulting header and row widths. csv.Sniffer is a heuristic too.
Create a counterexample: make one row whose quoted message contains a comma and a newline. Count logical CSV records separately from physical text lines. Then add a short row and choose whether your importer rejects just that record or the entire file. Preserve its record number and reason so the operator can correct the source. The exercise's data-row index is not necessarily the physical line number of a multiline CSV record.
Reference: CSV readers, dialects and dictionary-row behavior.
Quick practice
import csv, io
rows = list(csv.reader(io.StringIO('a,"say ""hi""",b')))
print(rows[0])text = "id,city\n1,\"Pune, MH\"\n2,Leeds\n"
import csv, io
print(len(list(csv.DictReader(io.StringIO(text)))))KeyErrorRun it, read the KeyError, then fix the DictReader call so the space doesn't become part of the key.
import csv, io
rows = list(csv.DictReader(io.StringIO("a;b\n1;2\n"), delimiter=";"))
print(rows[0]["a"])🎯 Your turn
Write read_csv(text). It returns a list of dicts, one per data row, keyed by
the header:
- strip a leading
""if there is one - pick the delimiter: whichever of
,;\t|appears most in the first line (ties go to,) - parse with
csv.DictReaderoverio.StringIO(text, newline=""), withskipinitialspace=True - strip whitespace from every key
Examples:
read_csv("id,name\n1,Ada\n")→[{"id": "1", "name": "Ada"}]read_csv('id,city\n1,"Pune, MH"\n')→[{"id": "1", "city": "Pune, MH"}]read_csv("id;amount\r\n7;3,50\r\n")→[{"id": "7", "amount": "3,50"}]
Hint: the first line is text.split("\n", 1)[0]. Take it after
stripping the BOM.
Press ▶ Run, try the chips in the Live App, then hit ✓ Check. Green means the supplied CSV contract passes; try the malformed-row cases above before broadening it.
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write count_fields(line) returning how many fields one CSV line holds. The starter uses split and gets quoted commas wrong: use csv.reader([line]) and take its first row.
Write column(text, name) returning the list of values in the column called name, in file order. Use csv.DictReader so the column is found by its header, not its position.
Write write_csv(rows). rows is a list of dicts that all share the same keys. Return CSV text with a header row (the first dict's keys, in order) and one line per dict, using \n line endings. Return "" for an empty list. Let csv.DictWriter do the quoting.
Write typed_rows(text, types). types maps a column name to one of "int", "float", "bool" or "str". Parse the CSV with DictReader and convert each listed column. An empty field becomes None whatever its type. For "bool", the values "true", "yes" and "1" (any case) are True and anything else is False. Columns not in types stay strings.
Write import_report(text). The CSV has at least the columns id and ms, and its delimiter may be , or ; (pick the one that appears more in the header line). Strip a leading BOM. For each data row, try int(row["ms"]). Return {"ok": count of good rows, "bad": [data-row numbers that failed, counting the first data row as 1], "total_ms": sum of the good ms}.
A colleague says: "Our exports never contain commas in the data, so line.split(",") is fine and faster." Explain what can go wrong, why it tends to go wrong silently rather than with an error, and why "never" is a weak guarantee for a file produced by someone else's program.