Sub topic 12
When split is not enough: quoted fields and the csv module
This chapter assumes you know str.split and str.join, including empty fields and maxsplit. It also assumes you can open a file with with open(...) and loop over it. Here you will see where splitting on a separator gives wrong answers, and how the standard csv module fixes that.
Why split breaks on real data
split(",") treats every comma as a boundary. In a CSV file, a comma inside a quoted field is part of the data. Consider this row:
row = 'a,"b,c",d'
print(row.split(",")) # ['a', '"b', 'c"', 'd']The intended row has three fields, but split returns four. The quote characters are also left in the result.
Plain splitting fails in four ways on this kind of data:
- A separator inside quotes is split apart.
- A doubled quote (
"") inside a quoted field stands for one literal quote.splitleaves it as two characters. - A newline inside a quoted field is part of the field.
splitlinesand line-by-line file iteration cut the record in half. - Spaces after the separator may or may not be part of the value, depending on the dialect.
You can patch each case with more string code, but you end up writing a parser. The csv module already is one.
Reading rows with csv.reader
csv.reader takes any iterable of lines and yields one list of strings per record. Here it handles the row from above:
import csv
row = 'a,"b,c",d'
print(next(csv.reader([row]))) # ['a', 'b,c', 'd']Two details matter here:
- The argument is a list containing one line. The reader expects an iterable of lines. If you pass a bare string, it iterates over characters.
- Each record is a list of
str. The reader never converts types, so"31"stays a string.
For a file, open it with newline="" and let the reader pull lines from it:
import csv
import tempfile
from pathlib import Path
path = Path(tempfile.gettempdir()) / "people.csv"
path.write_text('name,comment\r\nAnn,"likes tea, coffee"\r\nBob,\r\n', encoding="utf-8", newline="")
with path.open(newline="", encoding="utf-8") as f:
for record in csv.reader(f):
print(record)
# ['name', 'comment']
# ['Ann', 'likes tea, coffee']
# ['Bob', '']The last row shows a trailing empty field. Bob, yields ['Bob', ''], the same behavior as "Bob,".split(",").
Why newline="" matters
Normally, text-mode files translate line endings before your code sees them. The csv module needs the raw endings. That lets it tell a newline inside a quoted field (data) from the newline that ends a record. If you open the file without newline="", a \r\n embedded in a quoted field can be altered. The same applies when writing, where it can produce blank lines between rows on Windows.
Quoted newlines and doubled quotes
This example uses a field that spans two physical lines:
import csv
import io
text = 'id,note\r\n1,"line one\nline two"\r\n2,plain\r\n'
print(text.splitlines())
# ['id,note', '1,"line one', 'line two"', '2,plain']
rows = list(csv.reader(io.StringIO(text)))
print(rows)
# [['id', 'note'], ['1', 'line one\nline two'], ['2', 'plain']]splitlines returns four items, because it knows nothing about quotes. The reader returns three records, and the newline stays inside the second record's field.
A quote inside a quoted field is written by doubling it:
import csv
line = '1,"She said ""hi""",x'
print(next(csv.reader([line]))) # ['1', 'She said "hi"', 'x']The reader removes the outer quotes and collapses "" to ".
Writing rows with csv.writer
Joining is also unsafe for this data. Here is the naive version:
fields = ["Ann", 'said "hi", left']
print(",".join(fields)) # Ann,said "hi", leftA reader sees three fields in that line, not two. csv.writer adds quotes where needed and doubles embedded quotes:
import csv
import io
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(["name", "comment"])
writer.writerow(["Ann", 'said "hi", left'])
writer.writerow(["Bob", "line1\nline2"])
print(repr(buf.getvalue()))
# 'name,comment\r\nAnn,"said ""hi"", left"\r\nBob,"line1\nline2"\r\n'With the default QUOTE_MINIMAL setting, the writer quotes only fields that contain the delimiter, the quote character, or a line break. It also converts non-string values with str(), so you do not need the map(str, ...) step from the join chapter. None is written as an empty string.
Note the default line terminator is \r\n. If you write to a real file, open it with newline="" and the terminator is preserved exactly.
Round-tripping through the writer and reader returns the original data:
import csv
import io
original = [["a", "b,c", 'say "x"', "line1\nline2", ""]]
buf = io.StringIO()
csv.writer(buf).writerows(original)
buf.seek(0)
print(list(csv.reader(buf)) == original) # TrueThis guarantee does not hold for ",".join and split(",") once the data contains separators or quotes.
Reading rows as dictionaries
If the first row is a header, csv.DictReader uses it for field names:
import csv
import io
text = "name,age\nAnn,31\nBob,\n"
for record in csv.DictReader(io.StringIO(text)):
print(record)
# {'name': 'Ann', 'age': '31'}
# {'name': 'Bob', 'age': ''}Values are still strings, and a missing value is ''. Convert them yourself, for example int(record["age"]) after checking for an empty string. csv.DictWriter is the matching writer. You give it fieldnames, call writeheader(), then writerow() with dictionaries.
Dialects and options
CSV is not one format. Exports vary in delimiter, quote character, and spacing. You pass these as keyword arguments to the reader or writer:
import csv
print(next(csv.reader(['a;"b;c";d'], delimiter=";")))
# ['a', 'b;c', 'd']
spaced = 'a, "b,c"'
print(next(csv.reader([spaced])))
# ['a', ' "b', 'c"']
print(next(csv.reader([spaced], skipinitialspace=True)))
# ['a', 'b,c']The first call handles a semicolon-separated file, common in locales that use a comma as the decimal mark. The second pair shows the effect of a space after the comma. Without skipinitialspace=True, the quote is not at the start of the field, so the reader treats it as ordinary text. With it, the leading space is ignored and the quote opens a quoted field.
These options are the ones you will use most:
| Option | Default | Purpose |
|---|---|---|
| `delimiter` | `","` | Character that separates fields. Use `"\t"` for tab-separated files. |
| `quotechar` | `'"'` | Character that wraps quoted fields. |
| `skipinitialspace` | `False` | Ignore spaces right after a delimiter. |
| `quoting` | `csv.QUOTE_MINIMAL` | Controls which fields the writer quotes. `csv.QUOTE_ALL` quotes every field. |
| `strict` | `False` | If `True`, raise `csv.Error` on malformed input instead of guessing. |
| `lineterminator` | `"\r\n"` | Used by the writer only. The reader recognizes both `\n` and `\r\n`. |
Limits and gotchas
- Everything is a string. The
csvmodule does not know that"31"is a number or that""is missing. Convert and validate after reading. - Blank lines give empty lists. A blank line produces
[], so code that indexesrecord[0]should check for it. - Ragged rows are allowed. Rows can have different numbers of fields.
DictReaderfills missing values withNoneand puts extra values under the keyNone. Check lengths if your data must be rectangular. - Very large fields raise an error. The default limit is 131072 characters per field. You can raise it with
csv.field_size_limit(). - Encoding is your job. The module works on text, not bytes. Open the file with the right encoding. Spreadsheet exports from some tools start with a byte-order mark. For those,
encoding="utf-8-sig"strips it and keeps it out of the first header name. - The reader is lazy. It consumes a file as you iterate. Wrap it in
list(...)only when the data fits in memory, and do it before the file closes.
Choosing between split, re.split and csv
| Situation | Best tool | Reason |
|---|---|---|
| Fields never contain the separator, such as `"key=value"` or a log line with a fixed layout | `split`, `partition` | Simple, fast, and clear. |
| Several different separators, or a separator with variable spacing | `re.split` | A pattern describes all the boundaries. |
| Quotes, embedded separators or newlines, or data from a spreadsheet | `csv` | It implements the quoting rules. |
| Nested or hierarchical data | `json`, `tomllib`, or another real parser | A flat list of fields cannot represent it. |
A short rule: if you can imagine a value containing the separator, and you cannot ban that from the data, stop splitting and use a parser. The same rule applies on the way out. Use csv.writer when you produce CSV, not join.
Exercises
Exercise
The line 'x,"y,z",w'.split(",") returns four items. Write one expression that returns the intended three fields, and say what type each item has.
Show answer
next(csv.reader(['x,"y,z",w'])) returns ['x', 'y,z', 'w'] after import csv. The argument is a list holding one line, because the reader expects an iterable of lines. Each item is a str, because the csv module never converts types.
Exercise
You build a CSV line with ",".join(["Ann", "Smith, Jr.", "31"]) and send it to another program that reads it with csv.reader. How many fields does that program see, and how would you build the line instead?
Show answer
It sees four fields: Ann, Smith, Jr. and 31, because the comma inside the name is not quoted. Use csv.writer instead. Write the row with writerow(["Ann", "Smith, Jr.", "31"]) to an io.StringIO or a file opened with newline="". The writer produces Ann,"Smith, Jr.",31 followed by the line terminator.
Exercise
A file opened with open("data.csv") (no newline="") is read with csv.reader. Why is that risky, and what is the fix?
Show answer
Text mode translates line endings before the csv reader sees them, which can change a newline embedded inside a quoted field or confuse where records end. Open the file with open("data.csv", newline="", encoding="utf-8") so the reader receives the raw line endings and applies the quoting rules itself.