Python

Python csv — Reading Rows, DictReader, Writing, and Quoting

A comma-separated file looks simple until a field holds a comma of its own, a name carries a double quote, or a note runs onto a second line. The csv module in the standard library handles those cases with a small set of tools: a reader that returns each row as a list, a DictReader that returns each row as a dictionary keyed by the header, a writer that adds the quoting a field needs, and a DictWriter that writes dictionaries in a fixed column order. This guide runs each tool on a small sample, shows the exact text or values it produces, and ends with the traps that come from every value being a string.

Written November 13, 2026 · Tested with Python 3.12.3 · 12 min read

By the end of this guide
  • The main program: reading rows as lists
  • DictReader: rows keyed by the header
  • Writing rows with writer
  • DictWriter: writing dictionaries in a fixed order

Written November 13, 2026

Tested with Python 3.12.3

What this guide is

The csv module reads and writes files in the format that spreadsheet programs and many data tools share: rows separated by line endings, fields within a row separated by a delimiter, most often a comma, and fields that contain special characters wrapped in double quotes. The module works on any iterable of lines, so the programs here feed it a StringIO object from the io module, which behaves like a text file held in memory. Real code opens a file instead, with one detail that matters: the file should be opened with newline='' so the module sees the line endings as they are and quoted fields that hold newlines parse correctly. The sample data throughout is a three-column table of a name, a city, and a score. Small as it is, it shows every behavior that matters, including the one that surprises first-time users: every value the reader returns is a string, even the score.

The main program: reading rows as lists

The reader function takes an iterable of lines and returns an object that yields one list per row. Each list holds the fields of that row in order, as strings. The first row is data like any other, so a header line comes back as the first list and code decides what to do with it:

Python
import csv, io

sample = "name,city,score\nana,Toronto,9\nben,Calgary,10\n"
rows = list(csv.reader(io.StringIO(sample)))
print(rows[0])
print(rows[1])
print(rows[2])
print(len(rows))
print(type(rows[1][2]))

The exact output:

Config
['name', 'city', 'score']
['ana', 'Toronto', '9']
['ben', 'Calgary', '10']
3
<class 'str'>

The sample held three lines, so the list holds three rows, header included. The score in the second row prints as 9 but its type is str, which the last line proves. A reader is an iterator, so code can also loop over it one row at a time and handle a large file without holding the whole file in memory. Positional access is the reader's style: row[0] is the name and row[2] is the score, and nothing in the row itself says so. That is the gap the next tool fills.

DictReader: rows keyed by the header

DictReader reads the first row as field names and returns each later row as a dictionary keyed by those names. The fieldnames attribute holds the header it read. Code then asks for a column by name instead of by position, which survives a file whose columns arrive in a different order:

Python
import csv, io

sample = "name,city,score\nana,Toronto,9\nben,Calgary,10\n"
reader = csv.DictReader(io.StringIO(sample))
print(reader.fieldnames)
for row in reader:
    print(row["name"], row["score"])
    print(row)

The exact output:

Output
['name', 'city', 'score']
ana 9
{'name': 'ana', 'city': 'Toronto', 'score': '9'}
ben 10
{'name': 'ben', 'city': 'Calgary', 'score': '10'}

The values are still strings, as the printed dictionaries show. DictReader can also take field names from code, by passing a fieldnames list, in which case the first row is treated as data like the rest. If a file has no header, that is the form to use. The dictionary form is the common one for named data, because later edits to a program refer to columns by the same names the file uses, and a missing column fails at the lookup with the name in view.

Writing rows with writer

The writer function takes a writable object and returns an object with a writerow method for one row and a writerows method for many. It converts each value to text, adds quoting where a field needs it, and ends each row with the dialect's line terminator, which for the default dialect is a carriage return followed by a line feed. Reading the raw text back with repr makes those endings visible instead of letting the terminal hide them:

Python
import csv, io

output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["name", "city", "score"])
writer.writerow(["ana", "Toronto", 9])
writer.writerow(["ben", "Calgary", 10])
print(repr(output.getvalue()))
print(output.getvalue().splitlines())

The exact output:

Output
'name,city,score\r\nana,Toronto,9\r\nben,Calgary,10\r\n'
['name,city,score', 'ana,Toronto,9', 'ben,Calgary,10']

The repr line shows each row ending in \r\n, while splitlines shows the three plain lines with the endings stripped. The integer 9 went in as a number and came out as the text 9, because the file format holds only text. When the writable object is a real file, open it with newline='' on the write side as well: that stops the file layer from translating the line feed part of each ending and doubling the carriage return. The reader is built to accept the \r\n endings, so a file written this way reads back row for row.

DictWriter: writing dictionaries in a fixed order

DictWriter writes dictionaries. It needs the field names up front, as a fieldnames list, and that list fixes the column order for every row, whatever order each dictionary holds its keys in. The writeheader method writes the header row from those names, and writerows writes the data rows. Reading the result back with DictReader returns the same dictionaries, with the values as strings:

Python
import csv, io

output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=["name", "city", "score"])
writer.writeheader()
writer.writerows([
    {"name": "ana", "city": "Toronto", "score": 9},
    {"name": "ben", "city": "Calgary", "score": 10},
])
print(output.getvalue().splitlines())
print(list(csv.DictReader(io.StringIO(output.getvalue()))))

The exact output:

Config
['name,city,score', 'ana,Toronto,9', 'ben,Calgary,10']
[{'name': 'ana', 'city': 'Toronto', 'score': '9'}, {'name': 'ben', 'city': 'Calgary', 'score': '10'}]

A dictionary that leaves a field out gets the restval value for it, which is an empty string by default. A dictionary that carries a key outside fieldnames is a different case, and a harder one: it raises an error, as the traps section shows. That strictness is useful. A misspelled key in the data fails at the write instead of producing a file with a column silently missing.

Quoting: commas, double quotes, and newlines inside fields

A field that contains the delimiter, a double quote, or a line break cannot sit bare in a row, because a reader would split it at the comma or end the row early. The default quoting rule, QUOTE_MINIMAL, wraps only the fields that need it and doubles any double quote inside a field. Plain fields stay bare. The reader reverses all of it, so the values that come back match the values that went in:

Python
import csv, io

row = ["hello, world", 'say "hi"', "line one\nline two", "plain"]
output = io.StringIO()
csv.writer(output).writerow(row)
print(repr(output.getvalue()))
back = list(csv.reader(io.StringIO(output.getvalue())))
print(back[0])
print(back[0] == row)

The exact output:

Output
'"hello, world","say ""hi""","line one\nline two",plain\r\n'
['hello, world', 'say "hi"', 'line one\nline two', 'plain']
True

The repr line shows the three hard fields quoted, the quote inside the second field doubled, the newline kept inside the third field's quotes, and plain left bare. The round trip returns the original list exactly. This is why hand-built comma joining fails on real data and the module does not: joining strings with commas writes the comma inside a field as if it were a separator, and no later reader can tell the two apart.

Dialects and delimiters: semicolons and quoting every number as a number

A dialect is a named bundle of the reader and writer settings: the delimiter, the quoting rule, the quote character, and the line terminator. Code can pass single settings as arguments instead of naming a dialect. A file that uses semicolons as its separator is read and written with delimiter=';'. A different quoting rule, QUOTE_NONNUMERIC, quotes every non-numeric field on writing, and on reading it converts every unquoted field to a float:

Python
import csv, io

output = io.StringIO()
writer = csv.writer(output, delimiter=";")
writer.writerow(["name", "city", "score"])
writer.writerow(["ana", "Toronto", 9])
print(output.getvalue().splitlines())
print(list(csv.reader(io.StringIO(output.getvalue()), delimiter=";"))[1])
other = io.StringIO()
writer2 = csv.writer(other, quoting=csv.QUOTE_NONNUMERIC)
writer2.writerow(["name", "score"])
writer2.writerow(["ana", 9])
print(repr(other.getvalue()))
rows = list(csv.reader(io.StringIO(other.getvalue()), quoting=csv.QUOTE_NONNUMERIC))
print(rows[1])
print(type(rows[1][1]))

The exact output:

Config
['name;city;score', 'ana;Toronto;9']
['ana', 'Toronto', '9']
'"name","score"\r\n"ana",9\r\n'
['ana', 9.0]
<class 'float'>

The semicolon file splits on semicolons and returns the same strings. The QUOTE_NONNUMERIC text quotes the two names and leaves 9 bare, and the reader returns that field as the float 9.0, not the string '9' and not the integer 9. That conversion is the one place the module changes types on reading, and it applies to every unquoted field, so it suits files where unquoted always means a number. The other quoting rules are QUOTE_ALL, which quotes every field, and QUOTE_NONE, which quotes nothing and needs an escape character for fields that hold special characters.

Three traps in the string rows

Trap
The first trap is arithmetic on strings. Every value from a plain reader is text, so comparison and sorting follow text order, where '10' sorts before '9' because the comparison looks at the first character. Converting with int or float at the point of use gives numeric order and a sum that works. The second trap is a row with the wrong number of fields under DictReader: a short row fills the missing values with None, which is the default restval, and a long row collects its extra values in a list stored under the key None, which is the default restkey. Neither case raises an error, so a malformed file can pass through silently unless the code checks for None. The third trap is the DictWriter extra key, which does raise: the error is a ValueError naming the field that is not in fieldnames:
Python
import csv, io

print("10" < "9")
print(sorted(["9", "10", "100"]))
print(sum(int(value) for value in ["9", "10", "100"]))
sample = "name,city,score\nana,Toronto\nben,Calgary,10,extra\n"
for row in csv.DictReader(io.StringIO(sample)):
    print(row)
output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=["name", "city"])
try:
    writer.writerow({"name": "ana", "city": "Toronto", "score": 9})
except ValueError as error:
    print(type(error).__name__, error)

The exact output:

Output
True
['10', '100', '9']
119
{'name': 'ana', 'city': 'Toronto', 'score': None}
{'name': 'ben', 'city': 'Calgary', 'score': '10', None: ['extra']}
ValueError dict contains fields not in fieldnames: 'score'

Text order puts '10' and '100' before '9', the converted sum is 119, the short row shows None for the missing score, and the long row shows its extra value under the None key. The writer, handed a dictionary with a score key its fieldnames do not hold, raised ValueError and wrote nothing for that row.

Which choice for which job

Job Choice Why
Reading by position, or no header csv.reader Rows are plain lists in file order
Reading with a naming header csv.DictReader Columns are asked for by name
Writing list rows csv.writer One call per row, quoting added as needed
Writing dict rows csv.DictWriter The fieldnames list fixes the order, and a stray key fails at the write
Fields with commas, quotes, or newlines QUOTE_MINIMAL Only the fields that need quotes get them, and the reader restores the values
A semicolon file delimiter=';' Both sides must agree on the separator
Unquoted fields are numbers QUOTE_NONNUMERIC Writing leaves numbers bare, and reading returns them as floats

Checklist

  • Before reading a real file, open it with newline='' so quoted fields that hold newlines parse correctly.
  • Before trusting a column, remember every value is a string; convert with int or float where a number is needed, and never sort numeric columns as text.
  • Before writing dictionaries, fix the fieldnames list; it is the column order, the header, and the set of allowed keys in one place.
  • Before accepting DictReader rows from an outside file, check for a None value from a short row and a None key from a long row.
  • Before joining fields by hand, stop; a field with a comma or a quote in it needs the writer's quoting, not a join.
  • Before reading a file from another program, confirm its delimiter and quoting; a semicolon file read with the default comma returns one wide field per row.

Sources

  • Python Standard Library, csv — the reader and writer functions, DictReader and DictWriter, fieldnames, restval and restkey, the quoting rules including QUOTE_MINIMAL and QUOTE_NONNUMERIC, dialects and the delimiter setting, and the newline requirement for files.
  • Python Standard Library, io — the StringIO class used here as an in-memory text file that the csv reader and writer work on like any other iterable of lines or writable object.

Keep Exploring