Sub topic 10
Delimiters, quoting rules, and dialects
This chapter assumes you can read and write CSV with csv.reader and csv.writer. It also assumes you know to open CSV files with newline="" and an explicit encoding. Here you will learn how to handle CSV variants that use other separators or quoting rules.
Why "CSV" is not one format
CSV stands for comma-separated values, but real files differ. European spreadsheets often use a semicolon, because the comma is their decimal mark. Exports from other tools use tabs (TSV) or pipes. Some files quote every field, and others quote only when needed.
The csv module handles these differences through formatting parameters. You pass them to csv.reader, csv.writer, csv.DictReader, and csv.DictWriter.
Changing the delimiter and quoting
The delimiter parameter sets the character that separates fields. The quoting parameter sets when the writer wraps a field in quotes.
import csv
with open("semi.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f, delimiter=";", quoting=csv.QUOTE_ALL)
writer.writerow(["id", "note"])
writer.writerow([1, "a;b"])The file now contains:
"id";"note"
"1";"a;b"The value a;b contains the delimiter, so it must be quoted. With QUOTE_ALL, every field is quoted anyway.
To read the file, pass the same delimiter:
import csv
with open("semi.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f, delimiter=";"):
print(row)
# ['id', 'note']
# ['1', 'a;b']If you forget delimiter=";", each line comes back as one or two oddly split strings, and no error is raised. A wrong delimiter fails silently.
The four quoting modes
| Constant | Writer behavior | Reader behavior |
|---|---|---|
| `csv.QUOTE_MINIMAL` (default) | Quotes only fields containing the delimiter, the quote character, or a line break | Reads quoted fields normally |
| `csv.QUOTE_ALL` | Quotes every field | Reads quoted fields normally |
| `csv.QUOTE_NONNUMERIC` | Quotes every field that is not a number | Converts unquoted fields to `float` |
| `csv.QUOTE_NONE` | Never quotes; uses `escapechar` instead | Does not treat quotes as special |
QUOTE_NONNUMERIC on the reader side is a shortcut for number conversion, but it fails with ValueError on any unquoted field that is not a number. Explicit conversion, covered in the earlier chapter on type conversion, is usually safer.
QUOTE_NONE requires an escapechar if any field contains the delimiter. Without one, the writer raises csv.Error.
Quote characters inside fields
By default, a quote character inside a quoted field is doubled. The field say "hi" is written as "say ""hi""". The doublequote parameter controls this, and quotechar changes the quote character itself. You rarely need to change either unless a file comes from an unusual source.
Dialects: naming a set of settings
Repeating the same parameters is error-prone. A dialect bundles them under one name. Python ships with "excel" (the default), "excel-tab", and "unix". You can register your own:
import csv
csv.register_dialect("pipes", delimiter="|", quoting=csv.QUOTE_MINIMAL)
with open("pipes.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f, dialect="pipes")
writer.writerow(["name", "city"])
writer.writerow(["Ada", "Zürich"])
with open("pipes.csv", newline="", encoding="utf-8") as f:
print(list(csv.reader(f, dialect="pipes")))
# [['name', 'city'], ['Ada', 'Zürich']]Individual keyword arguments override the dialect, so csv.reader(f, dialect="pipes", delimiter="~") uses a tilde.
Guessing the format with Sniffer
When you receive files of unknown format, csv.Sniffer can guess the dialect from a sample:
import csv
sample = "id;note\n1;hello\n2;world\n"
dialect = csv.Sniffer().sniff(sample, delimiters=",;|\t")
print(repr(dialect.delimiter)) # ';'Restricting delimiters makes the guess more reliable. Sniffing is a heuristic, and it can fail on small or irregular samples by raising csv.Error. Use it as a fallback, not as a replacement for knowing your data.
Common errors
- Reading a semicolon file with the default dialect, which gives one field per row.
- Using
QUOTE_NONEwithout anescapecharwhen data contains the delimiter. - Forgetting
newline="", which can add blank lines on Windows or break quoted line breaks. - Passing a multi-character delimiter. The delimiter must be a single character.
Exercise
A colleague sends data.csv where fields are separated by tabs. Write the call that creates a reader for it, and say what happens if you omit your delimiter setting.
Show answer
Use csv.reader(f, delimiter="\t") (or dialect="excel-tab"), with the file opened using newline="" and an explicit encoding. If you omit it, the reader assumes commas, so each line is returned as a single string in a one-item list, and no error is raised.
Exercise
You write a file with csv.writer(f, quoting=csv.QUOTE_NONE) and a row contains "a,b". What happens, and how do you fix it?
Show answer
The writer raises csv.Error because it needs an escape character. Pass escapechar="\\" so the delimiter is written as a\,b, or use a quoting mode such as QUOTE_MINIMAL.