Reading and Writing CSV Files in Python

CSV (Comma-Separated Values) files are one of the most common formats for storing tabular data โ€” like spreadsheets or databases โ€” in plain text form. Each line in a CSV file represents a record, and columns are separated by commas.

Python's built-in csv module makes it simple to read, write, and process such files.

Importing the csv Module

To work with CSV files, first import the built-in csv module:

import csv

Reading a CSV File

To read a CSV file, open it in read mode and use csv.reader() or csv.DictReader().

Example 1: Using csv.reader()

import csv

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
Output:

['Name', 'Age', 'City', 'Profession', 'Salary']
['John Doe', '28', 'New York', 'Engineer', '72000']
...
Each row is returned as a list. The first row often contains headers like ["Name", "Age", "Marks"].


Example 2: Using csv.DictReader()

import csv

with open("students.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["Name"], "-", row["Marks"])
Output:

{'Name': 'John Doe', 'Age': '28', 'City': 'New York', 'Profession': 'Engineer', 'Salary': '72000'}
{'Name': 'Alice Smith', 'Age': '32', 'City': 'London', 'Profession': 'Data Analyst', 'Salary': '68000'}
...
Each row is returned as a dictionary with keys from the header row. Easier to access values by column name.

Writing to a CSV File

To write data into a CSV file, use csv.writer() or csv.DictWriter().

Example 1: Using csv.writer()

import csv

data = [
    ["Name", "Age", "Marks"],
    ["Alice", 20, 89],
    ["Bob", 22, 95],
    ["Charlie", 19, 78]
]

with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)
- writerow() โ†’ writes a single row
- writerows() โ†’ writes multiple rows
- Use newline="" to avoid blank lines between rows.


Example 2: Using csv.DictWriter()

import csv

data = [
    {"Name": "Alice", "Age": 20, "Marks": 89},
    {"Name": "Bob", "Age": 22, "Marks": 95},
    {"Name": "Charlie", "Age": 19, "Marks": 78}
]

with open("students_dict.csv", "w", newline="") as file:
    fieldnames = ["Name", "Age", "Marks"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    
    writer.writeheader()
    writer.writerows(data)
- Automatically maps dictionary keys to column headers.
- writeheader() writes the first row (column names).

Reading and Writing with Custom Delimiters

By default, the csv module uses commas (,) as separators. You can specify custom delimiters like tabs or semicolons.

import csv

with open("data.tsv", "r") as file:
    reader = csv.reader(file, delimiter="\t")
    for row in reader:
        print(row)

Summary

The csv module in Python provides a clean and efficient way to handle tabular data โ€” ideal for data science, analytics, and reporting. By mastering reader(), writer(), and DictReader()/DictWriter(), you can easily integrate CSV file operations into your applications.

Concept Description
csv.reader() Reads CSV as lists
csv.DictReader() Reads CSV as dictionaries
csv.writer() Writes rows to CSV files
csv.DictWriter() Writes dictionaries with headers
delimiter Defines a custom separator
In the next article, we'll explore JSON Handling in Python โ€” working with structured data for APIs and configurations.
Share this Article