Python Function Reference

csv.writer

Create an object that writes rows in CSV format.

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

Parameters

csvfileTextIO
A file open for writing with newline='', or io.StringIO.
dialectstr | Dialectoptional
A set of format settings; 'excel' by default, which is comma-separated CSV.
**fmtparamsAny
Individual settings, such as delimiter=';' or lineterminator for the line ending.

Return value

A writer object with the writerow(row) and writerows(rows) methods.

Examples

Writing a table to a file

Python 3.13
import csv

with open('people.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(['name', 'age'])
    writer.writerows([['Anna', 25], ['Boris', 31]])

with open('people.csv', encoding='utf-8') as file:
    print(file.read(), end='')
name,age
Anna,25
Boris,31

Quotes are added automatically

Python 3.13
import csv
import io

buffer = io.StringIO()
writer = csv.writer(buffer, lineterminator='\n')
writer.writerow(['Moscow', 'big, busy', 'say "hi"'])
print(buffer.getvalue(), end='')
Moscow,"big, busy","say ""hi"""

Details

Values containing the separator, quotes or a line break are quoted automatically, and quotes inside are doubled. Each row ends with \r\n, so open the file with newline='', otherwise empty lines appear between rows on Windows. Numbers and other values are written with str, and None as an empty string.

See also

Where to learn