Python CSV Files
What you will learn
- What a CSV file is
- Reading with
csv.readerandcsv.DictReader - Writing with
csv.writerandcsv.DictWriter - Why you must open CSV files with
newline="" - Quoting, other delimiters and bad rows
- Converting text to numbers
1. What is a CSV file?
CSV stands for comma-separated values: a plain text file where each line is a row and the values in a row are separated by commas. Spreadsheets and databases export and import it, so it is a common way to exchange tables:
name,age,city
Rina,25,Dhaka
Sam,22,"Khulna, BD"
You might think line.split(",") is enough, but look at the last line: the city Khulna, BD contains a comma, so it is wrapped in quotes, and a quote inside a value is written as two quotes ("Lee ""Jo"""). Values can even contain line breaks. Splitting by hand breaks on these cases; the csv module in the standard library handles all of them.
2. Writing with csv.writer
import csv
rows = [["name", "age", "city"],
["Rina", 25, "Dhaka"],
["Sam", 22, "Khulna, BD"],
['Lee "Jo"', 30, ""]]
with open("people.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(rows[0])
w.writerows(rows[1:])
print(repr(open("people.csv", newline="", encoding="utf-8").read()))
'name,age,city\r\nRina,25,Dhaka\r\nSam,22,"Khulna, BD"\r\n"Lee ""Jo""",30,\r\n'
writerow(list)writes one row;writerows(list_of_lists)writes many.- The writer adds quotes where needed and converts numbers to text.
- Lines end with
\r\n, the CSV standard.
Always newline=""
Notice newline="" in open. The csv module deals with line endings itself, and without this argument, on Windows, text mode converts \n again and you get extra blank lines. This is what happens to a one-row file written without it (the bytes read back in binary mode):
b'a,b\r\r\n'
The extra \r makes a blank line in many programs. Always open CSV files with newline="" (for reading and for writing).
Quick check: why not use `line.split(",")` to read a CSV?
Values may contain commas (inside quotes), quotes, or even line breaks. csv handles those.
3. Reading with csv.reader
with open("people.csv", newline="", encoding="utf-8") as f:
for row in csv.reader(f):
print(row)
['name', 'age', 'city']
['Rina', '25', 'Dhaka']
['Sam', '22', 'Khulna, BD']
['Lee "Jo"', '30', '']
Each row is a list of strings: the quotes are removed and Khulna, BD stays together. Every value is text, even '25'. Convert when you need numbers:
with open("people.csv", newline="", encoding="utf-8") as f:
r = csv.reader(f)
header = next(r) # the first row
data = list(r) # the rest
print(header, data[0], type(data[0][1]))
print(sum(int(row[1]) for row in data) / len(data))
['name', 'age', 'city'] ['Rina', '25', 'Dhaka'] <class 'str'>
25.666666666666668
next(r) takes the header row off the front (lesson 12.4). The average is of the three ages (25, 22, 30).
4. Reading with DictReader
csv.DictReader uses the first row as column names and gives each row as a dictionary, which is much clearer than numbered positions:
with open("people.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row, row["name"])
{'name': 'Rina', 'age': '25', 'city': 'Dhaka'} Rina
{'name': 'Sam', 'age': '22', 'city': 'Khulna, BD'} Sam
{'name': 'Lee "Jo"', 'age': '30', 'city': ''} Lee "Jo"
- The column names are in
reader.fieldnames. - Values are still strings. A typical clean-up step:
with open("people.csv", newline="", encoding="utf-8") as f:
people = [{"name": r["name"], "age": int(r["age"])} for r in csv.DictReader(f)]
print(people)
[{'name': 'Rina', 'age': 25}, {'name': 'Sam', 'age': 22}, {'name': 'Lee "Jo"', 'age': 30}]
5. Writing with DictWriter
with open("out.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["id", "item", "price"])
w.writeheader()
w.writerow({"id": 1, "item": "pen", "price": 1.5})
w.writerows([{"id": 2, "item": "ink, blue", "price": 4}])
print(repr(open("out.csv", newline="", encoding="utf-8").read()))
'id,item,price\r\n1,pen,1.5\r\n2,"ink, blue",4\r\n'
fieldnamesdecides the column order.writeheader()writes the first row.- A dictionary with a key that is not in
fieldnamesraisesValueError: dict contains fields not in fieldnames: 'extra'. - A missing key becomes an empty value.
6. Delimiters and quoting
The separator need not be a comma. Some regions use a semicolon (because the comma is their decimal mark), and TSV files use a tab:
import io
print(list(csv.reader(io.StringIO("a;b;c\n1;2;3\n"), delimiter=";")))
print(list(csv.reader(io.StringIO("x\ty\n1\t2\n"), delimiter="\t")))
[['a', 'b', 'c'], ['1', '2', '3']]
[['x', 'y'], ['1', '2']]
io.StringIO (lesson 15.3) lets these examples run without files; the same options work with real files.
Quoting options for writing:
buf = io.StringIO()
csv.writer(buf, quoting=csv.QUOTE_ALL).writerow(["a", 1, "b c"])
print(repr(buf.getvalue()))
buf = io.StringIO()
csv.writer(buf, lineterminator="\n").writerow(["a", "b,c"])
print(repr(buf.getvalue()))
'"a","1","b c"\r\n'
'a,"b,c"\n'
QUOTE_ALL quotes every field; lineterminator changes the line ending.
7. Messy real-world data
Real files often have problems. Know how csv reacts:
print(list(csv.reader(io.StringIO('a,"b\nc",d\n'))))
print(list(csv.reader(io.StringIO("a,b\n\n1,2\n"))))
print(list(csv.DictReader(io.StringIO("a,b\n1\n1,2,3\n"))))
[['a', 'b\nc', 'd']]
[['a', 'b'], [], ['1', '2']]
[{'a': '1', 'b': None}, {'a': '1', 'b': '2', None: ['3']}]
- A quoted value can contain a line break.
- A blank line gives an empty list
[]: checkif rowbefore using it. - A row with too few values gives
Nonefor the missing ones, and too many values go under the keyNone. - Empty cells are
'', and may not be convertible withint(): wrap conversions intry/except ValueError(lesson 14.1).
Excel's "CSV UTF-8" option writes a hidden marker at the start of the file, the BOM (byte order mark). If you read it as plain utf-8, the first column name becomes 'id'. Open such files with encoding="utf-8-sig", which removes it. You can also write with utf-8-sig so Excel recognises non-English text:
with open("bom.csv", "w", encoding="utf-8-sig", newline="") as f:
csv.writer(f).writerow(["café", "ঢাকা"])
print(repr(open("bom.csv", "rb").read()[:3]))
print(list(csv.reader(open("bom.csv", encoding="utf-8-sig", newline=""))))
b'\xef\xbb\xbf'
[['café', 'ঢাকা']]
(Printing the Bengali word needs a terminal that supports it. Programs that print such text on a Windows console may need UTF-8 enabled; the file itself is fine.)
For big tables with many columns and calculations, the third-party library pandas is the usual tool; the csv module is perfect for plain reading and writing, and needs nothing to install.
Worked example: a marks report
Read marks.csv, compute each student's average, label pass or fail, skip bad rows while reporting them, and write results.csv.
import csv
from pathlib import Path
Path("marks.csv").write_text(
"name,maths,science\nRina,80,90\nSam,45,50\nLee,60,\nAmy,x,70\n", encoding="utf-8")
good, skipped = [], []
with open("marks.csv", newline="", encoding="utf-8") as f:
for line_no, row in enumerate(csv.DictReader(f), start=2):
try:
maths, science = int(row["maths"]), int(row["science"])
except ValueError:
skipped.append((line_no, row["name"]))
continue
avg = (maths + science) / 2
good.append({"name": row["name"], "average": avg,
"result": "pass" if avg >= 50 else "fail"})
with open("results.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["name", "average", "result"])
w.writeheader()
w.writerows(good)
print(Path("results.csv").read_text(encoding="utf-8").replace("\r\n", "\n"), end="")
print("skipped:", skipped)
name,average,result
Rina,85.0,pass
Sam,47.5,fail
skipped: [(4, 'Lee'), (5, 'Amy')]
| Step | Idea |
|---|---|
enumerate(..., start=2) |
line numbers in the file (line 1 is the header) |
int(row["maths"]) in try |
the empty cell for Lee and the x for Amy raise ValueError |
continue after recording the problem |
bad rows are reported, not silently lost |
DictWriter with fieldnames |
fixed column order for the output |
.replace("\r\n", "\n") |
only for display here, to show clean lines |
The names and marks are made up. A real program might also write the skipped rows to a separate file for review.
Common mistakes
- Splitting lines on commas instead of using
csv. - Omitting
newline="", giving blank lines on Windows. - Forgetting that every value is text (
'10' + '5'is'105'; convert withintorfloat). - Assuming no blank rows or short rows in real files.
- Reading an Excel export without
utf-8-sig, gettingon the first header. - Opening without
encoding, so accented or non-English text breaks. - Treating the header as data, or forgetting it exists.
Key takeaways
- Use the
csvmodule; it handles quotes, commas and line breaks inside values. - Open CSV files with
newline=""andencoding="utf-8"(orutf-8-sigfor Excel files with a BOM). readergives lists,DictReadergives dictionaries keyed by the header;writerandDictWriterwrite them back.- Every value is a string: convert, and expect bad or missing cells.
- Change the separator with
delimiter=; control quoting withquoting=.
Practice
1. Why is newline="" needed?
Show answer
The csv module handles line endings itself. Without it, text mode can add an extra carriage return on Windows, producing blank lines.
2. What type is row[1] when csv.reader reads the row Rina,25,Dhaka?
Show answer
A string, '25'.
3. What does DictReader use for the dictionary keys?
Show answer
The first row of the file (the header), unless you give fieldnames.
4. How do you read a semicolon-separated file?
Show answer
csv.reader(f, delimiter=";")
5. Write a header and one row {"id": 1, "name": "Pen"} with DictWriter.
Show answer
with open("items.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["id", "name"])
w.writeheader()
w.writerow({"id": 1, "name": "Pen"})
6. The first column name reads 'id'. What is wrong?
Show answer
The file starts with a BOM. Open it with encoding="utf-8-sig".