csv.writer
writer(f).writerow(row) formats one row and calls f.write() with it. Every value goes through str(), None becomes an empty field — and the row ends in \r\n, which is why the file needs newline=''.
Demo
import csv, io buf = io.StringIO(newline='') w = csv.writer(buf) n = w.writerow(['Ada', 36, 1.5]) (n, buf.getvalue())
writerow returns whatever the file's write() returned — for io.StringIO and text files that is the number of characters written, including the two of "\r\n". In the quoting tab, None is written as an empty field: QUOTE_ALL and QUOTE_NONNUMERIC quote it (""), QUOTE_STRINGS and QUOTE_NOTNULL leave it bare so it can be told apart from the quoted empty string; QUOTE_NONNUMERIC leaves the int 36 bare. A quoting value outside 0–5 is TypeError: bad "quoting" value. Under QUOTE_NONE the escapechar is put before every delimiter and quote character; without one the writer raises csv.Error.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| csvfile | object with write() | yes | A file opened with newline='', io.StringIO, or anything with a write(str) method. |
| dialect | str | Dialect | no ('excel') | A registered name ('excel', 'excel-tab', 'unix') or a Dialect class/instance. |
| fmtparams | keyword arguments | no | Override single settings: delimiter, quotechar, escapechar, doublequote, quoting, lineterminator, skipinitialspace. |
Return value
_csv.writer — An object with writerow(row), writerows(rows) and a read-only dialect attribute.
Common patterns
import csv with open('out.csv', 'w', newline='', encoding='utf-8') as f: w = csv.writer(f) w.writerow(['name', 'age']) w.writerows([['Ada', 36], ['Bob', 41]])
import csv, io buf = io.StringIO(newline='') csv.writer(buf).writerows(rows) text = buf.getvalue()
import csv with open('out.csv', 'w', newline='', encoding='utf-8') as f: csv.writer(f, lineterminator='\n').writerows(rows)
Examples
Pitfalls
import csv, io buf = io.StringIO(newline='') csv.writer(buf).writerow('abc') buf.getvalue()
import csv, io buf = io.StringIO(newline='') csv.writer(buf).writerow(['abc']) buf.getvalue()
import csv with open('t.csv', 'w', newline='\r\n') as f: csv.writer(f).writerow(['a', 'b']) with open('t.csv', 'rb') as f: raw = f.read() raw
import csv with open('t.csv', 'w', newline='') as f: csv.writer(f).writerow(['a', 'b']) with open('t.csv', 'rb') as f: raw = f.read() raw
import csv line = ','.join(['Paris, TX', '2']) next(csv.reader([line]))
import csv, io buf = io.StringIO(newline='') csv.writer(buf).writerow(['Paris, TX', '2']) next(csv.reader([buf.getvalue()]))
When to use
- Exporting lists/tuples of values to a spreadsheet-readable file
- Generating CSV text for downloads or APIs (with io.StringIO)
- Rows that are dicts → csv.DictWriter
- Data with nesting → json
Notes
FAQ
You opened the file without newline='' on Windows. The writer ends rows with \r\n; text mode turns the \n into \r\n again. Use open(path, 'w', newline='', encoding='utf-8').