Sub topic 7
Reading and writing CSV with csv.reader and csv.writer
This chapter assumes you know basic Python syntax, how to use lists and strings, how to open files with the with statement, and how to handle exceptions. It builds on the previous chapter on opening files safely, because the csv module depends on how you open the file.
What the csv module does
CSV (comma-separated values) looks simple: one record per line, fields separated by commas. In practice, fields can contain commas, quotes, and even line breaks. Splitting a line on , breaks as soon as a field contains a comma. The csv module parses and writes these cases correctly, so use it instead of str.split.
The module has two basic tools:
csv.readerwraps a file and yields each row as a list of strings.csv.writerwraps a file and turns each list you give it into one CSV record.
Opening the file correctly
Both tools need the file opened in text mode with two settings:
newline=""lets thecsvmodule handle line endings itself. Without it, a quoted field that contains a line break can be read wrongly. On Windows, written files can also get blank lines between rows.encoding="utf-8"makes the encoding explicit, so the result does not depend on the platform default.
Writing rows
writer.writerow writes one row. writer.writerows writes any iterable of rows. The writer calls str() on each value, and it adds quotes only when a field needs them.
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 program prints:
['name', 'qty']
['apple', '3']
['pear, green', '5']The file on disk contains this text. Only the field with a comma is quoted:
name,qty
apple,3
"pear, green",5Reading rows
csv.reader is an iterator. Each step of the for loop reads one more line from the file and returns a list of strings. Every value is a string, even when it looks like a number. The reader does not know that 3 is a quantity.
import csv
with open("items.csv", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader)
total = 0
for name, qty in reader:
total += int(qty)
print(header, total)The call next(reader) takes the first row off the iterator, so the loop starts at the data. The program prints ['name', 'qty'] 8. The conversion int(qty) is your job. Chapter 9 covers type conversion in more detail.
Writing and reading are not symmetric
A round trip does not give back the same Python values. The writer accepts any value, but the reader returns only strings.
| You write | The file holds | You read back |
|---|---|---|
| `3` | `3` | `'3'` |
| `True` | `True` | `'True'` |
| `None` | an empty field | `''` |
| `"pear, green"` | `"pear, green"` | `'pear, green'` |
Because of this, None and an empty string look the same after a round trip. If the difference matters, decide on a convention, such as treating '' as missing, and apply it when you read.
Common errors
- Blank lines between rows on Windows. The file was opened without
newline="". - Garbled characters such as
ü. The file was written in UTF-8 but read with another encoding. Pass the sameencodingon both sides. ValueError: not enough values to unpack. A row has fewer fields than your loop expects. Blank lines in the middle of a file produce an empty list[]. Checkif not row: continuewhen the data may contain them.- Passing a string to
writerow.writer.writerow("abc")treats the string as an iterable and writesa,b,c. Always pass a list or tuple, such as["abc"]. - Using
+or.split(",")to build rows by hand. This fails for any field with a comma, a quote, or a line break.
Summary
- Open CSV files with
newline=""and an explicitencoding. csv.readeryields lists of strings, andcsv.writeraccepts lists of any values.- The writer quotes fields only when needed.
- Convert types yourself after reading.
Exercise
You run csv.writer(f).writerow(["id", "note"]) and then csv.writer(f).writerow([7, "a, b"]) on the same file. You read the file back with csv.reader. What does the second row look like in Python, and why is 7 not an integer?
Show answer
The second row is ['7', 'a, b']. The writer quoted the second field in the file (7,"a, b") because it contains a comma, and the reader removed the quotes again. The number 7 comes back as the string '7' because CSV stores only text, so the reader returns every field as a string. You must call int() yourself.
Exercise
A script writes rows to a CSV file on Windows and the output has an empty line after every row. What is the most likely cause and the fix?
Show answer
The file was opened without newline="". The text layer converted the \r\n line endings that the csv writer produces, so each row ended with an extra carriage return. Open the file with open(path, "w", newline="", encoding="utf-8").