How does Python’s CSV writer handle commas, quotes, and line breaks inside fields?
Quick answer
Python’s csv.writer handles these characters using CSV quoting rules. With its usual Excel dialect and default QUOTE_MINIMAL setting, it quotes a field when it contains a delimiter, quote character, or newline, and doubles quote characters inside a quoted field. [S1] Write rows with the CSV module rather than joining values with commas, which does not apply those rules. When writing to a file, open it with newline=''. [S1]
The question, the details, the next step.
A practical checklist
Pass each row to
writer.writerow()orwriter.writerows()as a sequence of field values.Open an output file with
newline=''when using Python’s CSV writer.Check that comma-containing values are quoted in the resulting text.
Check that embedded quotes are doubled and line breaks remain inside a quoted field.
Confirm the target application’s expected CSV dialect if it requires conventions different from Python’s defaults.
A few more useful answers
Does the CSV writer quote every field?
Not with the usual Excel dialect’s default QUOTE_MINIMAL setting: it quotes fields that need quoting because they contain the delimiter, a quote character, or a newline. [S1]
Does a line break inside a quoted field create a new CSV record?
Not by itself: a line break can be part of a quoted field, as in the example. The displayed text may span multiple physical lines even though it represents one field.
Will every program interpret this CSV the same way?
Not necessarily. Python’s documented defaults describe its usual Excel dialect, not every application’s conventions; check the receiving application’s dialect requirements. [S1]
Sources
References used for this guide.
- [S1] csv — CSV File Reading and Writing (Python 3.14 documentation) docs.python.org · Checked
