Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

CSV Files in Python

Learn how to read, write, create and process CSV files using Python.

What is a CSV File?

CSV stands for Comma-Separated Values.

A CSV file stores tabular data in a simple text format. Each row represents a record and values in a row are separated by a delimiter, commonly a comma.

Simple Definition: A CSV file stores data in rows and columns using a text-based format.

Simple CSV Example

A simple CSV file named students.csv can look like this:

Name,Course,Fees
Rahul,Python,45000
Priya,Java,40000
Amit,.NET,50000

The first row contains column headings and the following rows contain data records.

CSV File Diagram

CSV data can be understood as rows and columns.

Python Program

Reads or writes CSV data.

↓
CSV File

Rows and columns stored as text.

↓
Header

Name, Course, Fees

Row

Student record

Row

Another student record

↓
Processed Data

Python can read, modify and create CSV data.

The csv Module

Python provides the built-in csv module for working with CSV files.

import csv

The module provides classes and functions for reading and writing CSV data.

Reading a CSV File

We can use csv.reader() to read rows from a CSV file.

import csv

with open(
    "students.csv",
    "r",
    newline="",
    encoding="utf-8"
) as file:

    reader = csv.reader(file)

    for row in reader:

        print(row)

For the sample CSV file, the output will be similar to:

['Name', 'Course', 'Fees']
['Rahul', 'Python', '45000']
['Priya', 'Java', '40000']
['Amit', '.NET', '50000']

Accessing CSV Values

Each row returned by csv.reader() is represented as a list.

import csv

with open(
    "students.csv",
    "r",
    newline="",
    encoding="utf-8"
) as file:

    reader = csv.reader(file)

    for row in reader:

        print("Name:", row[0])
        print("Course:", row[1])
        print("Fees:", row[2])
Output
Name: Rahul
Course: Python
Fees: 35000
Name: Sneha
Course: .NET
Fees: 35000
Name: Amit
Course: Java
Fees: 30000

Skipping the Header Row

When the first row contains column names, we can read it separately.

import csv

with open(
    "students.csv",
    "r",
    newline="",
    encoding="utf-8"
) as file:

    reader = csv.reader(file)

    header = next(reader)

    print("Header:", header)

    for row in reader:

        print(row)

The next() function moves the reader to the next available row.

Output
Header: ['Name', 'Course', 'Fees']
['Rahul', 'Python', '35000']
['Sneha', '.NET', '35000']
['Amit', 'Java', '30000']

Reading CSV Using DictReader

csv.DictReader reads each row as a dictionary-like object using the header names as keys.

import csv

with open(
    "students.csv",
    "r",
    newline="",
    encoding="utf-8"
) as file:

    reader = csv.DictReader(file)

    for row in reader:

        print(row["Name"])
        print(row["Course"])
        print(row["Fees"])

This approach makes column-based access easier to read.

Output
Rahul
Python
35000
Sneha
.NET
35000
Amit
Java
30000

Writing a CSV File

We can use csv.writer() to write rows into a CSV file.

import csv

with open(
    "courses.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:

    writer = csv.writer(file)

    writer.writerow(
        ["Course", "Duration", "Fees"]
    )

    writer.writerow(
        ["Python", "6 Months", 45000]
    )

    writer.writerow(
        ["Java", "6 Months", 40000]
    )

The resulting CSV file will contain data similar to:

Course,Duration,Fees
Python,6 Months,45000
Java,6 Months,40000

Writing Multiple Rows

The writerows() method can write multiple rows at once.

import csv

rows = [
    ["Python", "6 Months", 45000],
    ["Java", "6 Months", 40000],
    [".NET", "5 Months", 50000]
]

with open(
    "courses.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:

    writer = csv.writer(file)

    writer.writerow(
        ["Course", "Duration", "Fees"]
    )

    writer.writerows(rows)

Writing CSV Using DictWriter

csv.DictWriter lets us write rows using dictionary values.

import csv

rows = [
    {
        "name": "Rahul",
        "course": "Python",
        "fees": 45000
    },
    {
        "name": "Priya",
        "course": "Java",
        "fees": 40000
    }
]

with open(
    "students.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:

    fieldnames = [
        "name",
        "course",
        "fees"
    ]

    writer = csv.DictWriter(
        file,
        fieldnames=fieldnames
    )

    writer.writeheader()

    writer.writerows(rows)

The dictionary keys become the column names.

Appending Data to a CSV File

We can use append mode "a" to add records without replacing existing rows.

import csv

with open(
    "students.csv",
    "a",
    newline="",
    encoding="utf-8"
) as file:

    writer = csv.writer(file)

    writer.writerow(
        ["Sneha", "MERN", 50000]
    )

The new record is added to the end of the file.

Using a Different Delimiter

CSV data does not always have to use commas. The delimiter parameter can specify another separator.

import csv

with open(
    "students.csv",
    "r",
    newline="",
    encoding="utf-8"
) as file:

    reader = csv.reader(
        file,
        delimiter=","
    )

    for row in reader:

        print(row)

Other delimiters can be used when the file format requires them.

Output
['Name', 'Course', 'Fees']
['Rahul', 'Python', '35000']
['Sneha', '.NET', '35000']
['Amit', 'Java', '30000']

Quoted CSV Values

CSV files may contain values that include commas or other special characters.

The CSV module handles standard quoting rules for reading and writing CSV data.

import csv

data = [
    ["Name", "City"],
    ["Rahul", "Pune, Maharashtra"],
    ["Priya", "Mumbai, Maharashtra"]
]

with open(
    "people.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:

    writer = csv.writer(file)

    writer.writerows(data)

The CSV module handles the required quoting when writing values containing delimiters.

Searching Data in a CSV File

We can read rows and search for a specific value.

import csv

search_name = "Rahul"

with open(
    "students.csv",
    "r",
    newline="",
    encoding="utf-8"
) as file:

    reader = csv.DictReader(file)

    for row in reader:

        if row["Name"] == search_name:

            print("Student found")
            print(row)
Output
Student found
{'Name': 'Rahul', 'Course': 'Python', 'Fees': '35000'}

Updating CSV Data

A common way to update CSV data is to read the existing rows, modify the required values and then write the rows back to the file.

import csv

rows = []

with open(
    "students.csv",
    "r",
    newline="",
    encoding="utf-8"
) as file:

    reader = csv.DictReader(file)

    fieldnames = reader.fieldnames

    for row in reader:

        if row["Name"] == "Rahul":

            row["Course"] = "Python Full Stack"

        rows.append(row)


with open(
    "students.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:

    writer = csv.DictWriter(
        file,
        fieldnames=fieldnames
    )

    writer.writeheader()
    writer.writerows(rows)

The selected record is updated and the complete CSV file is written again.

CSV File vs Normal Text File

CSV File Normal Text File
Designed for tabular data. General-purpose text storage.
Values are separated using delimiters. Does not require a tabular structure.
Easy to exchange between spreadsheet and data-processing applications. Commonly used for plain text.

Common CSV Tools

Tool Purpose
csv.reader() Read rows from a CSV file.
csv.writer() Write rows to a CSV file.
csv.DictReader() Read rows as dictionaries.
csv.DictWriter() Write dictionaries as CSV rows.
writerow() Write one row.
writerows() Write multiple rows.

Best Practices

  • Use the csv module rather than manually splitting and joining CSV text for normal CSV work.
  • Use newline="" when opening CSV files with the csv module.
  • Specify encoding="utf-8" when appropriate.
  • Use DictReader and DictWriter when named columns make the code easier to understand.
  • Validate file paths and input data when required.

Common Mistakes

  • Using the wrong column index.
  • Forgetting the header row when using DictReader.
  • Using an incorrect delimiter.
  • Forgetting newline="" while working with the CSV module.
  • Replacing the complete CSV file accidentally when append mode was required.

Example: Student CSV 📩👀

import csv

students = [
    {
        "Name": "Rahul",
        "Course": "Python",
        "Fees": 45000
    },
    {
        "Name": "Priya",
        "Course": "Java",
        "Fees": 40000
    },
    {
        "Name": "Amit",
        "Course": ".NET",
        "Fees": 50000
    }
]

with open(
    "students.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:

    fieldnames = [
        "Name",
        "Course",
        "Fees"
    ]

    writer = csv.DictWriter(
        file,
        fieldnames=fieldnames
    )

    writer.writeheader()
    writer.writerows(students)

print("CSV file created successfully")

This program creates a structured CSV file containing student information.

Practice Programs

  1. Create a CSV file containing student names and courses.
  2. Read the CSV file using csv.reader().
  3. Read the same file using DictReader.
  4. Create a CSV file using csv.writer().
  5. Create a CSV file using DictWriter.
  6. Append a new student record.
  7. Search for a student by name.
  8. Update a student's course and rewrite the CSV file.

Summary

CSV stands for Comma-Separated Values and is commonly used for storing tabular data. Python provides the built-in csv module to read and write CSV files. We can use reader() and DictReader() for reading data, and writer() and DictWriter() for writing data. CSV files are useful for storing and exchanging structured row-and-column data.