Sub topic 12
When split is not enough: quoted fields and the csv module
This chapter assumes you know str.split, str.join, and basic loops and generator expressions. It shows where plain splitting gives wrong answers and how the csv module fixes them.
Why split breaks on quoted fields
str.split(",") treats every comma as a separator. It has no idea that a comma can be part of a value. In CSV (comma-separated values) text, a field that contains the separator is wrapped in double quotes, so "b,c" is one field.
import csv
row = 'a,"b,c",d'
print(row.split(",")) # ['a', '"b', 'c"', 'd']
print(next(csv.reader([row]))) # ['a', 'b,c', 'd']The plain split returns four items and keeps stray quote characters. csv.reader returns the three fields the writer intended and removes the quotes.
How csv.reader works
csv.reader takes any iterable of lines, such as an open file or a list of strings. It returns an iterator that yields one list of strings per record. Each record is parsed with these rules:
- A field in quotes can contain the separator.
- A doubled quote inside a quoted field (
"") stands for one literal quote. - A quoted field can span several lines.
- Every value comes back as a
str, even if it looks like a number.
import csv
import io
text = 'name,note\nAda,"likes ""tea"", coffee"\nLin,"two\nlines"\n'
for record in csv.reader(io.StringIO(text)):
print(record)
# ['name', 'note']
# ['Ada', 'likes "tea", coffee']
# ['Lin', 'two\nlines']The last record contains a newline inside one field. text.splitlines() would cut that record in two, so line-based splitting fails here as well.
Writing with csv.writer
The reverse problem exists for join. ",".join(fields) does not add quotes, so a field containing a comma changes the number of columns when the text is read back. csv.writer quotes only the fields that need it.
import csv
import io
fields = ["a", "b,c", 'say "hi"']
print(",".join(fields)) # a,b,c,say "hi"
buffer = io.StringIO()
csv.writer(buffer).writerow(fields)
print(repr(buffer.getvalue())) # 'a,"b,c","say ""hi"""\r\n'The writer ends each record with \r\n by default. The result survives a round trip: reading it back with csv.reader returns the original three fields.
Other separators and dictionaries
Many files use tabs or semicolons. Pass delimiter to change the separator. csv.DictReader uses the first row as column names and yields a dictionary per record.
import csv
import io
text = "id;city\n1;Oslo\n2;Rome\n"
for rec in csv.DictReader(io.StringIO(text), delimiter=";"):
print(rec["id"], rec["city"])
# 1 Oslo
# 2 RomeChoosing between split and csv
| Situation | Tool |
|---|---|
| Whitespace-separated words you generated yourself | `split()` |
| A fixed `key=value` pair | `partition` or `split("=", 1)` |
| Exported spreadsheets, user-supplied files | `csv.reader` |
| Writing rows that may contain commas or quotes | `csv.writer` |
Common errors
- Splitting each line of a CSV file with
line.split(","). This works on simple test data and fails when real data contains a quoted comma. - Passing a single string to
csv.reader. A string is an iterable of characters, so you get one record per character. Wrap it in a list or useio.StringIO. - Expecting numbers. Convert with
int()orfloat()yourself. - Building output with
",".join(...)when values come from users.
Exercise
A line is '1,"Smith, Jo",42'. What does line.split(",") return, and how do you get ['1', 'Smith, Jo', '42']?
Show answer
line.split(",") returns ['1', '"Smith', ' Jo"', '42'], because it splits at the comma inside the quotes. Use next(csv.reader([line])), which respects the quoting and returns ['1', 'Smith, Jo', '42'].
Exercise
Why does ",".join(["x", "y,z"]) not survive a round trip through csv.reader, and what replaces it?
Show answer
The joined text x,y,z has no quotes, so the reader sees three fields instead of two. Use csv.writer(...).writerow(["x", "y,z"]), which writes x,"y,z" and reads back as two fields.