Lesson · Standard Data Formats
CSV
55 min readCSV
CSV is deceptively simple because quoting, delimiters, embedded newlines, and dialects complicate manual parsing. Python's `csv` module exists to handle those details correctly.
Learning goals
- Read rows with
csv.readerandcsv.DictReaderand explain what each yields per line. - Write rows with
csv.writerandDictWriter, including a header row and quoting decisions. - Explain why files used with the
csvmodule must be opened withnewline="". - Predict when a field needs quoting and how the module resolves it, instead of splitting by hand.
- Describe what
DictReaderdoes with the first line and what happens to an unexpected column count.
Mental model
CSV handling splits into two symmetric pairs: reader and writer work in lists of strings, DictReader and DictWriter work in dicts keyed by the header row, and both pairs rely on the same dialect rules for commas, quotes, and newlines. Pick the pair that matches where your data lives (positional versus named columns); either way the file is a plain text file and the module decides how each field is quoted.
Core idea
A CSV file is a text file whose commas are not reliable delimiters until the quoting rules are applied, so the csv module's job is to be the only place that decides where fields begin and end. The reader hands you lists or dicts of strings, the writer turns lists or dicts into quoted text, and the header line is what makes the dict forms possible. Treat every field as a string until you convert it yourself.
csv.reader
csv.reader parses rows while honoring CSV quoting and delimiter rules. Open text files with newline='' when using the csv module so it can manage newline semantics correctly.
csv.writer
csv.writer takes a file-like object and returns a writer whose writerow(iterable) method converts the iterable to one CSV line, adding quoting where fields contain the delimiter, quotes, or newlines, and returns the number of characters written. writerows applies the same to an iterable of rows, and dialect arguments such as delimiter and quoting are fixed on the writer.
DictReader
DictReader wraps rows as dictionaries keyed by the first line (or by a fieldnames argument you supply), and yields one dict per data row. All values arrive as strings, a column missing from a short row comes back as None, and extra values collect in a list under the restkey name when one is given.
DictWriter
DictWriter writes dictionaries as rows and requires fieldnames up front so it can emit the header with writeheader(). Missing keys are written as restval (an empty string by default), and keys not listed in fieldnames raise ValueError unless extrasaction='ignore' is set.
Delimiters and quoting
CSV quoting rules allow delimiters, quotes, and newlines to appear inside fields. Use the csv module with the correct dialect instead of splitting lines manually.
Walkthrough
StringIO('name,score\nAda,98\nGrace,99\n')gives the reader a file-like object, so the example runs without touching disk; the embedded\ncharacters mark the three lines.csv.DictReader(source)consumes the first line as the header, so each loop row is a dict like{"name": "Ada", "score": "98"}; both values are strings, which is whyint(row["score"])is explicit.- The loop runs twice, once per data line, and the reader advances the shared StringIO position, so a second loop would yield nothing.
- Predict before running: the two printed lines, then what
rowcontains if one data row had three fields.
Experiments to try
- Print
reader.fieldnamesbefore the loop and confirm it holds the header list; then passfieldnames=["name", "score"]and check what happens to the first line. - Put a comma inside a field (
'name,note\nAda,"scores, ranked"\n') and iterate; the reader returns the quoted field as one string, which manualsplit(",")would break. - Write two rows with
csv.writerinto aStringIOand printrepr()of the result; add a field containing a quote and see the doubled-quote escaping. - Read a row with fewer fields than the header and print the dict; the missing column appears as
None.
Common mistakes
- Opening the file without
newline="": the interpreter's newline translation runs before the csv parser and rewrites\r\nsequences, including ones inside quoted fields, so one record can split into two rows. - Splitting lines with
text.split(",")instead of using the module: any field containing a comma, a quote, or a newline comes out wrong, and the failure depends on the data rather than the code. - Converting fields without checking for short rows:
DictReaderfills missing columns withNone, soint(row["score"])raisesTypeErroron theNonerather than the expectedValueError. - Passing a bare string to
writerowinstead of a list: a string is iterable, sowriterow("Ada")writes one field per character rather than one field.
Practice: Easy
- Use
csv.readeron the worked example'sStringIOand print each row as alist; compare the output with theDictReaderversion line by line. - Add a third data line with a comma inside quotes and confirm the parsed field count stays two.
- Write two rows with
csv.writerinto aStringIOand print the text; identify where quoting was added.
Practice: Medium
- Convert parsed rows into records with converted types (
nameasstr,scoreasint); collect rows whose score is not numeric into abad_rowslist instead of crashing. - Round-trip a list of dicts through
DictWriterand back throughDictReaderusing aStringIO; assert the records equal the originals including header order. - Refactor a hand-split parser (
line.split(",")) to the csv module and list the inputs that change behavior, such as quoted commas and CRLF endings.
Practice: Hard
- Design a CSV validator: required columns by name, per-column type rules, and a report of row numbers with violations. Test it on a file with a missing column, a bad number, and a clean row.
- Build a converter between two dialects (comma-separated and semicolon-separated, different quoting) that streams rows through one reader and one writer without loading the file; explain why
newline=""is still required. - Investigate external compatibility: write a UTF-8 file with a non-ASCII header and read it back; test the same round trip with
encoding="utf-8-sig"and describe what a spreadsheet consumer would need.
Lesson checklist
- I can read the same data with
csv.readerandDictReaderand describe the difference. - I can write rows with
csv.writerand explain where quoting appears. - I can explain why
newline=""is required and what breaks without it. - I can convert every field explicitly and handle
Nonefrom short rows.
Remember
CSV is a dialect of plain text, not a data structure, so the `csv` module owns the two decisions that make it parseable: where fields end and how special characters are quoted. Use `reader` and `writer` for positional data, `DictReader` and `DictWriter` when the header names the columns, open the file with `newline=""`, and remember that every value arrives as a string.
Interview angles
What is the main purpose of **csv.reader**?+
csv.reader parses rows while honoring CSV quoting and delimiter rules. Open text files with newline='' when using the csv module so it can manage newline semantics correctly.
What should you pay attention to when using **csv.writer**?+
csv.writer turns each iterable you pass to writerow into one properly quoted line and returns the number of characters written; pass a list of fields, because a bare string is iterated character by character. Delimiter and quoting are configured once on the writer.
How does **DictReader** fit into this lesson?+
DictReader reads the first line as the header and yields one dict per data row, with all values as strings; missing columns become None and extra values collect under restkey. Conversion of those strings stays your job.
Why can a short row make `int(row["score"])` raise `TypeError` instead of `ValueError`?+
DictReader fills columns missing from a short row with None, and int(None) raises TypeError because None is the wrong type; a non-numeric string would raise ValueError instead. Validate the field before converting.