Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

csv.writer

Serializes field sequences into delimited rows and quotes fields as needed.

Version: Python 3.14; repository image, production runtime not attested

Syntax

csv.writer(csvfile, /, dialect='excel', **fmtparams)

Serializes field sequences into delimited rows and quotes fields as needed.

Under the default dialect, fields containing delimiters are quoted and embedded quotes are doubled. With QUOTE_NONE and an escapechar, the delimiter is escaped instead.

Serialize each row of fields to a text stream supporting write(). Open files with newline='' and set lineterminator if the output requires a particular line ending. With the default minimal quoting a comma quotes its field and internal quotes are doubled. None and an empty string can become indistinguishable in the default format; other nonstring values are converted with str(). With QUOTE_NONE and a configured escapechar, the writer can escape a delimiter without quoting the field.

import csv, io
out = io.StringIO(newline="")
w = csv.writer(out, lineterminator="\n")
w.writerow(["a,b", 'say "yes"', None, 4])
assert out.getvalue() == '"a,b","say ""yes""",,4\n'
raw = io.StringIO(newline="")
csv.writer(raw, quoting=csv.QUOTE_NONE, escapechar="\\", lineterminator="\n").writerow(["a,b"])
assert raw.getvalue() == "a\\,b\n"

Examples

import csv
from io import StringIO

out = StringIO(newline="")
w = csv.writer(out, lineterminator="\n")
w.writerow(["a,b", 'say "yes"'])
print(out.getvalue(), end="")

Result

"a,b","say ""yes"""

Serialize each row of fields to a text stream supporting write(). Open files with newline='' and set lineterminator if the output requires a particular line ending. With the default minimal quoting a comma quotes its field and internal quotes are doubled. None and an empty string can become indistinguishable in the default format; other nonstring values are converted with str(). With QUOTE_NONE and a configured escapechar, the writer can escape a delimiter without quoting the field.

Sources