Reading history

Python CSV Files: Read and Write with the csv Module

6 min read 1 views

Read and write CSV files in Python with csv.reader, csv.writer, DictReader and DictWriter, handle quoted commas, newline and encoding, and other delimiters.

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.reader and skipping the header
  • Why newline="" and encoding matter
  • Working with column names using DictReader and DictWriter
  • 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.reader reads 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() or float() 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.StringIO treats a string like a file, which is handy for examples and tests. With a real file, pass the open file object instead.
  • DictReader turns each row into a dictionary keyed by the header, so you write s["marks"] instead of row[2]. Code keeps working if the column order changes.
  • The averages are computed by grouping rows by department in a dictionary.
  • DictWriter needs fieldnames, which sets the columns and their order. writeheader() writes the header row, and extrasaction="ignore" skips keys that are not listed, such as dept.
  • The delimiter argument reads other formats, such as semicolon-separated files common in Europe, or "\t" for tab-separated files.

csv Module Essentials

TaskCode
Open for readingopen(path, newline="", encoding="utf-8")
Rows as listscsv.reader(f)
Rows as dictionariescsv.DictReader(f)
Write listscsv.writer(f).writerow(row) / writerows(rows)
Write dictionariescsv.DictWriter(f, fieldnames=[...])
Other separatordelimiter=";" or delimiter="\t"
Quote every valuequoting=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

  1. Splitting lines by hand with split(","), which breaks on quoted values.
  2. Forgetting that every value is a string, so "88" + "92" gives "8892".
  3. Leaving out newline="", which can add blank rows on Windows.
  4. 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.
  • DictReader and DictWriter let you work with column names.
  • All values are read as strings; convert them before calculating.

Next: Python pathlib: Working with Files and Folders.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *