Sub topic 7
Reading and writing CSV with csv.reader and csv.writer
This chapter covers the two basic tools of Python's csv module: csv.reader and csv.writer. I assume you can open files with with, loop over lists, and catch exceptions. You should also know why files need an explicit encoding, which the file handling chapter at the start of this tutorial covered.
Why not just split on commas?
A CSV (comma-separated values) file stores a table as text. Each line is a row, and commas separate the fields. The simplest parser is line.split(","), and it breaks quickly:
- A field can contain a comma, such as
pear, green. The format handles this by wrapping the field in double quotes. - A field can contain a double quote. The format doubles it:
say ""hi"". - A field can contain a line break, so one record can span several lines of the file.
The csv module handles all three cases. It is in the standard library, so there is nothing to install.
Opening CSV files correctly
Open every CSV file with two arguments that you would not normally need for a plain text file:
newline=""turns off Python's own line-ending translation. Thecsvmodule needs to see the raw line endings. Without it, line breaks inside quoted fields can be corrupted on read, and Windows can write blank lines between rows.encoding="utf-8"makes the encoding explicit instead of relying on the platform default.
import csv
with open("data.csv", "r", newline="", encoding="utf-8") as f:
...Use the same two arguments for writing, with mode "w".
Writing rows with csv.writer
csv.writer(f) wraps a file object and gives you two methods:
writerow(row)writes one row from a list or tuple.writerows(rows)writes every row from an iterable of rows.
import csv
rows = [["name", "qty"], ["apple", "3"], ["pear, green", "5"]]
with open("items.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
with open("items.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f):
print(row)The file now contains three lines:
name,qty
apple,3
"pear, green",5The writer added quotes around pear, green on its own. The loop prints each row as a list of strings:
['name', 'qty']
['apple', '3']
['pear, green', '5']How values are converted on write
The writer calls str() on every value, so you can pass numbers directly. None is the exception: it is written as an empty field.
import csv
with open("mixed.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerow([1, 2.5, True, None, "x"])The line written is 1,2.5,True,,x. This conversion works in one direction only. Nothing in the file records that 1 was an integer or that True was a boolean, so reading it back gives you strings.
Line endings
By default the writer ends each row with \r\n. This comes from the excel dialect, and it happens on every operating system because newline="" stops Python from translating it. Most tools accept this. If you want Unix line endings, pass lineterminator="\n" to csv.writer.
Reading rows with csv.reader
csv.reader(f) is an iterator. Each time you take the next item, you get one record as a list of strings. A record is not always one line of the file, because a quoted field can contain line breaks.
import csv
with open("notes.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["id", "note"])
writer.writerow([1, "line one\nline two"])
with open("notes.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f):
print(row)The output shows the embedded newline preserved inside the second record:
['id', 'note']
['1', 'line one\nline two']The file has three physical lines but only two records. reader.line_num counts physical lines read from the source, not records, so do not use it as a record counter.
The reader accepts any iterable of strings, not only files. That makes it easy to test parsing code without touching the disk:
import csv
lines = ["a,b", "1,2", '"x,y",3']
print(list(csv.reader(lines)))The result is [['a', 'b'], ['1', '2'], ['x,y', '3']].
Handling the header row
csv.reader does not treat the first row specially. The header is just the first list. To separate it from the data, call next() on the reader:
import csv
with open("items.csv", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader)
total = sum(int(row[1]) for row in reader)
print(header, total) # ['name', 'qty'] 8After next(reader), the loop continues from the second row. Two points to remember:
- On an empty file,
next(reader)raisesStopIteration. Pass a default if that can happen:next(reader, None). - Because you access fields by position (
row[1]), a reordered column breaks the code silently. The next chapter'sDictReaderavoids this by using the header names.
Everything is a string
The reader never guesses types. A field containing 3 arrives as "3", and an empty field arrives as "", not None. This is the most common source of bugs when reading CSV:
import csv
with open("items.csv", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
next(reader)
for name, qty in reader:
print(name, qty * 2)This prints apple 33 and pear, green 55, because "3" * 2 repeats the string. No error is raised. Convert explicitly with int(qty), float(...), or a date parser. Later chapters cover conversion and its failure cases.
Quoting rules
The writer decides quoting per field. With the default setting csv.QUOTE_MINIMAL, it quotes a field only if it contains the delimiter, the quote character, or a line break. Reading reverses this: surrounding quotes are removed, and doubled quotes inside a field become single quotes.
import csv
import io
buffer = io.StringIO()
csv.writer(buffer).writerow(['say "hi"', "a,b"])
print(buffer.getvalue().strip())The output is "say ""hi""","a,b". Both fields were quoted. The first field's inner quotes were doubled, and the second field was quoted because it contains a comma.
The module's other settings, such as semicolon delimiters and QUOTE_ALL, are covered in the dialects chapter.
Rows of different lengths
CSV has no enforced shape. The reader returns whatever it finds, so rows can have different numbers of fields:
import csv
lines = ["a,b,c", "1,2", "3,4,5,6", ""]
for row in csv.reader(lines):
print(len(row), row)This prints:
3 ['a', 'b', 'c']
2 ['1', '2']
4 ['3', '4', '5', '6']
0 []Note the last line: a blank line gives an empty list, not a list with one empty string. Code such as row[0] then raises IndexError. Validate before you index:
import csv
def read_pairs(path):
with open(path, newline="", encoding="utf-8") as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
if not row:
continue # skip blank lines
if len(row) != 2:
raise ValueError(f"line {reader.line_num}: expected 2 fields, got {len(row)}")
yield row[0], row[1]This is a generator, so it also reads one row at a time. Including reader.line_num in the message lets the user find the bad line in the file.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Blank line after every row on Windows | File opened without `newline=""` | Add `newline=""` |
| `UnicodeDecodeError` on read | File is not in the encoding you passed | Pass the correct `encoding`, or `utf-8-sig` for files from Excel |
| A stray `\ufeff` at the start of the first header | Byte order mark (BOM) read as text | Open with `encoding="utf-8-sig"` |
| `TypeError: can't multiply sequence by non-int` or silent string repetition | Values are strings | Convert with `int()` or `float()` |
| `IndexError` on `row[0]` | Blank line gives an empty list | Check `if not row` first |
| Columns shifted or merged | The file uses `;` or tabs as delimiter | Pass `delimiter=` (see the dialects chapter) |
A csv.Error is raised for malformed input in some cases, for example a field larger than the default limit of 131072 characters. Catch it like any other exception, and raise the limit with csv.field_size_limit() only if you trust the file.
Summary of the API
csv.writer(f)giveswriterowandwriterows. It converts values withstr(), writesNoneas an empty field, quotes only when needed, and ends rows with\r\n.csv.reader(f)yields onelist[str]per record. It does not skip the header, does not convert types, and does not enforce row length.- Open both files with
newline=""and an explicitencoding.
Exercise
A file scores.csv has the header player,points followed by rows such as Mia,12. Write a function total_points(path) that returns the sum of the points as an int using csv.reader. Skip the header and any blank lines. What would go wrong if you removed the int() conversion?
Show answer
def total_points(path):
total = 0
with open(path, newline="", encoding="utf-8") as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
if not row:
continue
total += int(row[1])
return total
(with import csv at the top). Without int(), total += row[1] would raise a TypeError because you cannot add a str to an int. If total started as a string, the values would be concatenated into text such as "1285" instead of added. This is the "everything is a string" rule: the reader never converts types for you.