all Python 3Files & I/Ofunction
csv.writer()
csv — writing
Returns a CSV writer object: writerow() and writerows() turn lists of values into file lines with the right quoting and delimiters.
Syntax
w = csv.writer(csvfile, dialect='excel', **fmtparams); w.writerow(row)
Lines end with '\r\n' (the excel dialect requires it), so a file opened without newline='' on Windows gets '\r\r\n' — and blank lines appear between records. Values go through str(), and None is written as an empty string, so reading back will not give None. Quotes inside a field are doubled automatically; do not escape them by hand.
Examples
import csv
import io
out = io.StringIO()
csv.writer(out).writerow(['a,b', 'he said "hi"', 3, None])
print(repr(out.getvalue())) # → '"a,b","he said ""hi""",3,\r\n'
import csv
with open('out.csv', 'w', newline='', encoding='utf-8') as f:
csv.writer(f).writerows([['x', 'y'], [1, 2]])
with open('out.csv', newline='', encoding='utf-8') as f:
print(list(csv.reader(f))) # → [['x', 'y'], ['1', '2']]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy