CSV (comma-separated values) is the simplest way to move tables between programs. Excel, Google Sheets, databases and websites can all export and import it. It looks easy to handle with split(","), until a value such as “Rahman, Tania” contains a comma of its own. Python’s built-in csv module handles quoting, separators and line endings correctly. This lesson shows how to write and read CSV files, use column names with DictReader and DictWriter, and summarise the data.
In this lesson you will learn
- Writing rows with
csv.writer - Reading rows with
csv.readerand skipping the header - Why
newline=""andencodingmatter - Working with column names using
DictReaderandDictWriter - Other delimiters such as semicolons and tabs
You should know file handling and dictionaries.
Writing and Reading Rows
import csv
import os
import tempfile
folder = tempfile.mkdtemp()
path = os.path.join(folder, "students.csv")
# Writing rows; newline="" stops blank lines appearing on Windows
rows = [
["name", "city", "cgpa"],
["Nusrat", "Dhaka", 3.82],
["Arif", "Chattogram", 3.41],
["Rahman, Tania", "Dhaka", 3.95], # a comma inside a value
]
with open(path, "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
with open(path, encoding="utf-8") as f:
print(f.read())
# Reading rows back as lists of strings
with open(path, newline="", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader)
print("header:", header)
for row in reader:
print(row, "-> cgpa as number:", float(row[2]))
Output
name,city,cgpa
Nusrat,Dhaka,3.82
Arif,Chattogram,3.41
"Rahman, Tania",Dhaka,3.95
header: ['name', 'city', 'cgpa']
['Nusrat', 'Dhaka', '3.82'] -> cgpa as number: 3.82
['Arif', 'Chattogram', '3.41'] -> cgpa as number: 3.41
['Rahman, Tania', 'Dhaka', '3.95'] -> cgpa as number: 3.95
csv.writer(f).writerows(rows)writes a list of rows. Each row is a list, and numbers are converted to text automatically.- “Rahman, Tania” contains a comma, so the writer wrapped it in double quotes. A plain
split(",")would have broken it into two columns;csv.readerreads it back correctly as one value. - Open CSV files with
newline="". The csv module handles line endings itself, and without this you can get blank lines between rows on Windows. - Give an
encoding, usually"utf-8", so names in Bangla or other scripts are saved correctly. Use"utf-8-sig"if Excel must open the file and show non-English text properly. next(reader)reads the header row so the loop sees only data.- Every value comes back as a string. Convert with
int()orfloat()before doing maths.
DictReader and DictWriter
import csv
import io
data = """name,dept,marks
Nusrat,CSE,88
Arif,EEE,72
Tania,CSE,95
Rafi,EEE,64
Mitu,CSE,79
"""
# DictReader uses the header row as keys
reader = csv.DictReader(io.StringIO(data))
students = list(reader)
print(students[0])
# Group and average by department
totals = {}
for s in students:
d = totals.setdefault(s["dept"], [0, 0])
d[0] += int(s["marks"])
d[1] += 1
for dept, (total, count) in totals.items():
print(f"{dept}: average {total / count:.1f}")
# DictWriter writes dictionaries; extra columns are easy to add
out = io.StringIO()
writer = csv.DictWriter(out, fieldnames=["name", "marks", "grade"], extrasaction="ignore",
lineterminator="\n")
writer.writeheader()
for s in students:
s["grade"] = "A" if int(s["marks"]) >= 80 else "B"
writer.writerow(s)
print(out.getvalue(), end="")
# Other separators: semicolons or tabs
print(next(csv.reader(io.StringIO("Dhaka;22;humid"), delimiter=";")))
Output
{'name': 'Nusrat', 'dept': 'CSE', 'marks': '88'}
CSE: average 87.3
EEE: average 68.0
name,marks,grade
Nusrat,88,A
Arif,72,B
Tania,95,A
Rafi,64,B
Mitu,79,B
['Dhaka', '22', 'humid']
io.StringIOtreats a string like a file, which is handy for examples and tests. With a real file, pass the open file object instead.DictReaderturns each row into a dictionary keyed by the header, so you writes["marks"]instead ofrow[2]. Code keeps working if the column order changes.- The averages are computed by grouping rows by department in a dictionary.
DictWriterneedsfieldnames, which sets the columns and their order.writeheader()writes the header row, andextrasaction="ignore"skips keys that are not listed, such asdept.- The
delimiterargument reads other formats, such as semicolon-separated files common in Europe, or"\t"for tab-separated files.
csv Module Essentials
| Task | Code |
|---|---|
| Open for reading | open(path, newline="", encoding="utf-8") |
| Rows as lists | csv.reader(f) |
| Rows as dictionaries | csv.DictReader(f) |
| Write lists | csv.writer(f).writerow(row) / writerows(rows) |
| Write dictionaries | csv.DictWriter(f, fieldnames=[...]) |
| Other separator | delimiter=";" or delimiter="\t" |
| Quote every value | quoting=csv.QUOTE_ALL |
For large data analysis, the pandas library’s read_csv loads a CSV into a table with types detected automatically. The csv module is ideal for small scripts and when you want no extra dependencies.
Common Mistakes
- Splitting lines by hand with
split(","), which breaks on quoted values. - Forgetting that every value is a string, so
"88" + "92"gives"8892". - Leaving out
newline="", which can add blank rows on Windows. - Not handling the header row, then failing to convert “marks” to a number.
Practice Exercises
Exercise 1. Using the data from the second example, print the name of the student with the highest marks.
Show answer
best = max(students, key=lambda s: int(s["marks"]))
print(best["name"]) # Tania
Exercise 2. Write a list of dictionaries [{"city": "Dhaka", "temp": 31}, {"city": "Sylhet", "temp": 27}] to weather.csv.
Show answer
import csv
rows = [{"city": "Dhaka", "temp": 31}, {"city": "Sylhet", "temp": 27}]
with open("weather.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["city", "temp"])
writer.writeheader()
writer.writerows(rows)
Frequently Asked Questions
How do I read an Excel .xlsx file?
The csv module cannot read .xlsx files. Either save the sheet as CSV from Excel, or use a library such as openpyxl or pandas, which can read Excel files directly.
Why does Excel show strange characters in my CSV?
Excel may not detect UTF-8 automatically. Write the file with encoding="utf-8-sig", which adds a marker that tells Excel the file is UTF-8.
Summary
- Use the csv module, not
split, so quoted values work. - Open files with
newline=""and an explicit encoding. DictReaderandDictWriterlet you work with column names.- All values are read as strings; convert them before calculating.
