Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

csv.reader

Parses delimited rows while honoring quoted fields and escaped quotes.

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

Syntax

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

Parses delimited rows while honoring quoted fields and escaped quotes.

Parsed fields normally remain strings even if they resemble integers. A quoted delimiter stays inside its field.

Read an iterable of text lines and yield lists of fields. Open text files with newline='' so the CSV parser handles embedded line breaks. Under the default dialect fields are strings; QUOTE_NONNUMERIC instead converts unquoted numeric text to float. In the sample the quoted comma stays in a,b and the trailing comma produces an empty field. QUOTE_NONNUMERIC attempts to convert every nonempty unquoted field, so abc raises ValueError. An empty unquoted field remains an empty string.

import csv, io
r = csv.reader(io.StringIO('7,"a\nb",\n', newline=""))
assert next(r) == ["7", "a\nb", ""]
assert r.line_num == 2
assert next(csv.reader(['7,"2"'], quoting=csv.QUOTE_NONNUMERIC)) == [7.0, "2"]
assert next(csv.reader([',7'], quoting=csv.QUOTE_NONNUMERIC)) == ["", 7.0]
try:
    next(csv.reader(["abc"], quoting=csv.QUOTE_NONNUMERIC))
except ValueError:
    pass
else:
    raise AssertionError

Examples

import csv
row = next(csv.reader(['7,"a,b",']))
print(row)
print(type(row[0]).__name__)

Result

['7', 'a,b', '']
str

Read an iterable of text lines and yield lists of fields. Open text files with newline='' so the CSV parser handles embedded line breaks. Under the default dialect fields are strings; QUOTE_NONNUMERIC instead converts unquoted numeric text to float. In the sample the quoted comma stays in a,b and the trailing comma produces an empty field. QUOTE_NONNUMERIC attempts to convert every nonempty unquoted field, so abc raises ValueError. An empty unquoted field remains an empty string.

Sources