LearnContact
Lesson 5322 min read

CSV Handling

Learn how to read and write CSV files in Python using the csv module, including DictReader and DictWriter for header-based access.

Introduction

CSV (Comma-Separated Values) is one of the simplest and most widely used formats for storing tabular data. Spreadsheets, databases, and data science tools can all export and import CSV files, which makes it an extremely common format to work with in real Python programs.

Python's built-in csv module handles the tricky edge cases of CSV parsing for you — like commas inside quoted values — so you rarely need to split lines manually.

What You Will Learn
  • What a CSV file is and how it is structured.
  • How to read rows with csv.reader.
  • How to write rows with csv.writer.
  • Why CSV files should be opened with newline='' when writing.
  • How DictReader and DictWriter make header-based access easier.

What is a CSV File?

A CSV file stores data as plain text, with each line representing one row and commas separating each column value. The first row is often (but not always) a header row naming each column.

students.csv
name,age,grade
Alex,16,A
Maya,15,B
Riya,16,A

Plain Text

CSV files can be opened and edited in any text editor.

Row-Based

Each line represents one record, like one row in a spreadsheet.

Comma-Separated

Commas separate each column value within a row.

Universally Supported

Excel, Google Sheets, and databases can all import and export CSV.

The csv Module

Python's built-in csv module provides reader and writer objects that handle the details of parsing and formatting CSV rows correctly, including values that contain commas or quotes.

csv.reader()

Reads CSV rows as plain lists of strings.

csv.writer()

Writes lists of values as CSV rows.

csv.DictReader()

Reads rows as dictionaries, using the header row as keys.

csv.DictWriter()

Writes dictionaries as CSV rows using specified field names.

Reading CSV Files

csv.reader() wraps an open file and lets you loop over it row by row. Each row comes back as a plain list of strings.

read_csv.py
import csv

with open("students.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
Output
['name', 'age', 'grade']
['Alex', '16', 'A']
['Maya', '15', 'B']
['Riya', '16', 'A']

Notice the first row is the header. If you want to skip it, you can call next(reader) once before your loop, or use DictReader as shown further below.

Writing CSV Files

csv.writer() lets you write rows to a file one at a time with writerow(), or all at once with writerows().

write_csv.py
import csv

rows = [
    ["name", "age", "grade"],
    ["Alex", 16, "A"],
    ["Maya", 15, "B"],
]

with open("output.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(rows)

print("CSV written successfully")
Output
CSV written successfully

The resulting output.csv file contains three lines of comma-separated values, matching the students.csv format shown earlier.

Why newline='' Matters

On Windows, text files normally translate every \n into \r\n automatically when writing. The csv module already adds its own line endings, so without newline='', you can end up with blank lines between every row.

Always Use newline='' When Writing CSV

Open CSV files for writing with open("file.csv", "w", newline="") — this disables Python's automatic newline translation and lets the csv module handle line endings correctly on every platform.

Correct vs Incorrect
# Incorrect - may produce extra blank lines on Windows
with open("output.csv", "w") as file:
    writer = csv.writer(file)

# Correct
with open("output.csv", "w", newline="") as file:
    writer = csv.writer(file)

DictReader & DictWriter

Working with plain lists means remembering which index corresponds to which column. DictReader and DictWriter solve this by using the header row as dictionary keys, so you can access columns by name instead of position.

dict_reader.py
import csv

with open("students.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["name"], "-", row["grade"])
Output
Alex - A
Maya - B
Riya - A
dict_writer.py
import csv

students = [
    {"name": "Alex", "age": 16, "grade": "A"},
    {"name": "Maya", "age": 15, "grade": "B"},
]

with open("output.csv", "w", newline="") as file:
    fieldnames = ["name", "age", "grade"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(students)

print("Done")
Output
Done
DictWriter Needs fieldnames

Unlike csv.writer(), DictWriter requires a fieldnames list up front so it knows the column order, and writeheader() must be called explicitly to write the header row.

Practical Example: Summing a Column

A very common real-world task is reading a CSV file and calculating something from one of its columns — like a total, average, or count. DictReader makes this straightforward since values can be accessed by column name.

sales.csv
product,quantity,price
Pen,10,5
Notebook,4,40
Eraser,20,2
sum_column.py
import csv

total_revenue = 0

with open("sales.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        quantity = int(row["quantity"])
        price = int(row["price"])
        total_revenue += quantity * price

print("Total Revenue:", total_revenue)
Output
Total Revenue: 290

Every value read from a CSV file is a string, even numbers like "10" or "5" — so they must be converted with int() or float() before being used in calculations.

Common Mistakes

Avoid These Mistakes
  • Forgetting newline="" when opening a file for writing, causing extra blank lines.
  • Trying to do math on CSV values without converting them to int or float first.
  • Assuming column order in csv.writer() matches DictWriter's fieldnames automatically.
  • Not calling writeheader() before writerows() with DictWriter.
  • Assuming every CSV file uses a comma as the delimiter — some use semicolons or tabs, which requires the delimiter parameter.

Best Practices

  • Always open CSV files for writing with newline="".
  • Prefer DictReader/DictWriter when column names matter more than position.
  • Convert numeric string values with int() or float() before calculations.
  • Use the with statement so files are always closed properly.
  • Check the delimiter used in real-world files before assuming it is a comma.

Frequently Asked Questions

Are values from a CSV file always strings?

Yes. The csv module reads everything as text, so numbers must be explicitly converted with int() or float() before use in calculations.

What if my CSV file uses semicolons instead of commas?

Pass the delimiter parameter, for example csv.reader(file, delimiter=";"), to tell the module which character separates values.

Do I need newline="" when reading CSV files too?

It is mainly required when writing on Windows. Reading is generally safe without it, but many developers add it consistently for both operations out of habit.

Can I use pandas instead of the csv module?

Yes, pandas offers a more powerful read_csv() function for data analysis, but the built-in csv module is lighter weight and perfect for simple scripts without extra dependencies.

What happens if a row has fewer columns than the header?

With DictReader, missing values are filled with None by default, so you should check for None before using a value in calculations.

Key Takeaways

  • CSV files store tabular data as comma-separated plain text.
  • csv.reader()/csv.writer() work with plain lists of values.
  • csv.DictReader()/csv.DictWriter() work with dictionaries, keyed by column name.
  • Always use newline="" when opening a CSV file for writing.
  • Values read from CSV are always strings and must be converted for math.

Summary

The csv module gives you everything needed to read and write tabular data files without manually splitting strings on commas, handling the edge cases of quoting and line endings for you.

In this lesson, you learned how to read and write CSV files with csv.reader()/csv.writer(), why newline="" matters on Windows, how DictReader/DictWriter simplify header-based access, and how to calculate a total from a CSV column.

Lesson 53 Completed
  • You can read and write CSV files using the csv module.
  • You understand why newline="" is required when writing.
  • You can use DictReader and DictWriter for header-based access.
  • You are ready to learn about logging in Python.
Next Lesson →

Logging