all Python 3Files & I/Ofunction
csv.reader()
csv — reading
Reads CSV row by row: returns an iterator that yields each record as a list of strings. It handles quotes, commas inside fields and escaping for you.
Syntax
csv.reader(csvfile, dialect='excel', **fmtparams)
Every value comes back as a string, even numbers: you must convert '30' to int yourself. Open the file with newline='', or a quoted field containing a line break is parsed wrongly. Do not split lines with split(','): '"Ivanov, Ivan"' breaks in two, while reader returns one field. The reader is single-use like any iterator: a second pass yields nothing.
Examples
import csv
import io
buf = io.StringIO('name,age\n"Ivanov, Ivan",30\n')
for row in csv.reader(buf):
print(row) # → ['name', 'age'] / ['Ivanov, Ivan', '30']
import csv
with open('data.csv', 'w', newline='', encoding='utf-8') as f:
f.write('a;b\n1;2\n')
with open('data.csv', newline='', encoding='utf-8') as f:
rows = list(csv.reader(f, delimiter=';'))
print(rows) # → [['a', 'b'], ['1', '2']]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy