Sub topic 10
Delimiters, quoting rules, and dialects
This chapter assumes you can already use csv.reader, csv.writer, DictReader, and DictWriter. It also assumes you open CSV files with newline="" and an explicit encoding. Here you will learn how the csv module decides where one field ends and the next begins, and how to change those rules for files that are not plain comma-separated.
Why "CSV" is not one format
"CSV" has no single binding standard. Different tools produce files that differ in a few ways:
- Spreadsheet programs in many European locales write semicolons, because the comma is the decimal separator there.
- Database exports often use tabs (TSV) or pipes (
|). - Some tools quote every field. Others quote only when they must.
- Some tools escape a quote character with a backslash. Others double it.
The csv module groups these choices into a dialect. A dialect is a named set of formatting parameters that a reader or writer follows. If you pick the wrong dialect, you rarely get an error. You usually get silently wrong columns.
import csv
import io
data = "id;note\n1;a,b\n"
print(list(csv.reader(io.StringIO(data))))
print(list(csv.reader(io.StringIO(data), delimiter=";")))Output:
[['id;note'], ['1;a', 'b']]
[['id', 'note'], ['1', 'a,b']]The first call treats the whole header as one column and splits the second row at the wrong place. The second call gives the intended result.
The formatting parameters
Every reader and writer accepts these parameters as keyword arguments. The defaults come from the excel dialect.
| Parameter | Default | Meaning |
|---|---|---|
| `delimiter` | `,` | One character that separates fields. |
| `quotechar` | `"` | One character that wraps fields containing special characters. |
| `quoting` | `csv.QUOTE_MINIMAL` | When the writer adds quotes, and how the reader interprets them. |
| `doublequote` | `True` | A quote inside a quoted field is written as two quotes. |
| `escapechar` | `None` | A character that escapes the delimiter, or the quote when `doublequote` is false. |
| `skipinitialspace` | `False` | Reader ignores spaces directly after a delimiter. |
| `lineterminator` | `"\r\n"` | What the writer puts at the end of each row. The reader ignores it. |
| `strict` | `False` | Reader raises `csv.Error` on bad input instead of guessing. |
The delimiter and quote character must each be exactly one character. Passing delimiter="::" raises TypeError. If your file uses a multi-character separator, split the lines yourself or preprocess them.
Choosing a delimiter
Set the delimiter on the reader and the writer. A tab-separated file works the same way:
import csv
import io
tsv = "name\tcity\nAda\tLondon\nGrace\tNew York\n"
for row in csv.reader(io.StringIO(tsv), delimiter="\t"):
print(row)The module also ships a ready-made csv.excel_tab dialect, so dialect="excel-tab" has the same effect.
Whitespace after delimiters
Some hand-written files put a space after each comma. By default the space becomes part of the value:
import csv
import io
line = 'a, b, "c d"\n'
print(next(csv.reader(io.StringIO(line))))
print(next(csv.reader(io.StringIO(line), skipinitialspace=True)))Output:
['a', ' b', ' "c d"']
['a', 'b', 'c d']Without skipinitialspace, the space before the third quote means the quote is no longer at the start of the field. The reader then treats the quotes as literal text. This is a common source of stray quote characters in parsed data.
Quoting modes
A writer must quote a field when it contains the delimiter, the quote character, or a line break. The quoting parameter controls what else it quotes. The module defines four classic constants.
| Constant | Writer behavior | Reader behavior |
|---|---|---|
| `QUOTE_MINIMAL` | Quotes only fields that need it. | Default parsing. |
| `QUOTE_ALL` | Quotes every field. | Same as minimal. |
| `QUOTE_NONNUMERIC` | Quotes every field that is not a number. | Converts every unquoted field to `float`. |
| `QUOTE_NONE` | Never quotes. Special characters are escaped with `escapechar`. | Treats quote characters as ordinary text. |
Python 3.12 added QUOTE_STRINGS and QUOTE_NOTNULL. They let a writer tell None apart from an empty string. Check your Python version before relying on them.
Here is the same data written under each classic mode:
import csv
import io
rows = [["id", "note"], [1, 'say "hi"'], [2, "a,b"]]
modes = [
("MINIMAL", dict(quoting=csv.QUOTE_MINIMAL)),
("ALL", dict(quoting=csv.QUOTE_ALL)),
("NONNUMERIC", dict(quoting=csv.QUOTE_NONNUMERIC)),
("NONE", dict(quoting=csv.QUOTE_NONE, escapechar="\\")),
]
for name, options in modes:
buf = io.StringIO()
csv.writer(buf, lineterminator="\n", **options).writerows(rows)
print(f"--- {name}")
print(buf.getvalue(), end="")Output:
--- MINIMAL
id,note
1,"say ""hi"""
2,"a,b"
--- ALL
"id","note"
"1","say ""hi"""
"2","a,b"
--- NONNUMERIC
"id","note"
1,"say ""hi"""
2,"a,b"
--- NONE
id,note
1,say \"hi\"
2,a\,bThe example sets lineterminator="\n" only so the output prints cleanly. For files, keep the default and open the file with newline="".
How quotes are escaped inside a field
By default, doublequote=True: a literal " inside a quoted field becomes "". This is what Excel and most tools expect. If a consumer expects backslash escaping instead, set both options:
import csv
import io
buf = io.StringIO()
writer = csv.writer(buf, doublequote=False, escapechar="\\", lineterminator="\n")
writer.writerow([1, 'say "hi"'])
print(buf.getvalue(), end="")This prints 1,"say \"hi\"". With doublequote=False and no escapechar, the writer cannot represent the quote and raises csv.Error.
Reading with QUOTE_NONNUMERIC
On the reading side, QUOTE_NONNUMERIC is a shortcut for type conversion. Every unquoted field becomes a float:
import csv
import io
text = '"name","qty"\n"apple",3\n"pear",5\n'
for row in csv.reader(io.StringIO(text), quoting=csv.QUOTE_NONNUMERIC):
print(row)Output:
['name', 'qty']
['apple', 3.0]
['pear', 5.0]Note the 3.0. You get floats, never ints. If an unquoted field is not a valid number, such as an empty value, the reader raises ValueError. For anything beyond clean, fully quoted files, convert types explicitly as you did in the previous chapters.
Dialects
Repeating five keyword arguments on every call is error-prone. A dialect bundles them under a name.
Built-in dialects
Call csv.list_dialects() to see what is registered. You get excel, excel-tab, and unix. The unix dialect quotes all fields and ends rows with \n.
import csv
print(sorted(csv.list_dialects()))Registering your own
csv.register_dialect(name, **params) registers a dialect by keyword arguments. You can also pass a subclass of csv.Dialect or an existing dialect such as csv.excel. Subclassing csv.excel is convenient because you override only what differs:
import csv
class Pipe(csv.excel):
delimiter = "|"
quoting = csv.QUOTE_MINIMAL
csv.register_dialect("pipe", Pipe)
csv.register_dialect("eu", delimiter=";", quoting=csv.QUOTE_ALL)
rows = [["id", "price"], [1, "3,50"], [2, "12,00"]]
with open("prices.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f, dialect="eu").writerows(rows)
with open("prices.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f, dialect="eu"):
print(row)The file contains "id";"price", then "1";"3,50", and so on. The reader returns ['1', '3,50'] because the semicolon is the delimiter and the decimal comma is ordinary text.
DictReader and DictWriter accept the same dialect argument and the same keyword overrides.
Overrides beat the dialect
Keyword arguments take precedence over the named dialect, so you can start from a registered dialect and adjust one setting:
import csv
import io
text = "id|note\n1|it's fine\n"
reader = csv.reader(io.StringIO(text), dialect="pipe", quotechar="'")
print(list(reader))Registration is global to the process. Registering a name twice replaces the earlier definition, so pick distinctive names in libraries.
Guessing the dialect with Sniffer
When you receive files from unknown sources, csv.Sniffer can infer the delimiter and quote character from a sample of the text:
import csv
sample = "id;note\n1;hello\n2;world\n"
dialect = csv.Sniffer().sniff(sample, delimiters=",;|\t")
print(repr(dialect.delimiter))This prints ';'. The returned object is a dialect class you can pass straight to csv.reader.
Sniffing is a heuristic. It can raise csv.Error: Could not determine delimiter on short or irregular samples, and it can guess wrong when a file has only one column. Always restrict it with the delimiters argument, read a sample of a few kilobytes, and then call f.seek(0) before parsing the whole file. Treat Sniffer().has_header() the same way: it is a guess, not a fact.
Choosing settings: a decision guide
Common errors and edge cases
- One giant column. A file that parses into a single field per row almost always has a different delimiter than you assumed. Print the first line with
repr()to see the real separator, including tabs. - Stray BOM in the first header. Excel often saves UTF-8 files with a byte order mark. The first column name then starts with
\ufeff. Open the file withencoding="utf-8-sig"to strip it. - Quotes that survive parsing. Spaces before an opening quote, as shown earlier, leave the quotes in the data. Use
skipinitialspace=True. - Line breaks inside quoted fields. A quoted field may span several physical lines. This only works if you open the file with
newline="". Without it, the file object translates line endings beforecsvsees them, which can corrupt embedded newlines. - Field too large. A malformed file with an unclosed quote can swallow the rest of the file into one field. The reader then raises
csv.Error: field larger than field limit (131072). Fix the data first. Raise the limit withcsv.field_size_limit()only if the large fields are legitimate. - Silent acceptance of bad input. With
strict=False, the reader accepts malformed quoting. Setstrict=Truewhen you would rather fail loudly, for example on a data-validation step. - Mismatched round trips. Whatever dialect you write with, a reader must use the same one. Store the delimiter and quoting choice in documentation or in the file name, such as
data.tsv.
Exercises
Exercise
What does list(csv.reader(io.StringIO("a;b\n1;2,5\n"))) return with the default settings, and which single keyword argument fixes it?
Show answer
It returns [['a;b'], ['1;2', '5']]: the default comma delimiter splits at the comma in 2,5 and never splits at the semicolon. Passing delimiter=";" gives [['a', 'b'], ['1', '2,5']].
Exercise
You call csv.writer(f, quoting=csv.QUOTE_NONE).writerow(["a,b"]). What happens, and how do you make it work?
Show answer
The writer raises csv.Error ("need to escape, but no escapechar set") because the field contains the delimiter and there is no quoting to protect it. Add escapechar="\\" so the row is written as a\,b. The program that reads the file must use the same escape character.
Exercise
Register a dialect named "semi" with a semicolon delimiter and QUOTE_ALL, then write the row [1, "x;y"] to a StringIO using it. What is the output line?
Show answer
Code: csv.registerdialect("semi", delimiter=";", quoting=csv.QUOTEALL); buf = io.StringIO(); csv.writer(buf, dialect="semi").writerow([1, "x;y"]). The value is "1";"x;y" followed by the default \r\n line terminator.