Python

CSV File Handling in Python, CBSE Class 12 Tutorial with Programs

Complete guide to CSV file handling in Python for CBSE Class 12. Learn csv.reader, csv.writer, DictReader, DictWriter with practical programs and output.

CSV (Comma Separated Values) file handling is part of the CBSE Class 12 Computer Science syllabus. CSV files are used to store tabular data in plain text, where each line is a row and values are separated by commas. This guide covers everything from basic reading and writing to practical exam programs.

What is a CSV File?

A CSV file is a simple text file that stores data in a table-like format. Each line represents one row, and values within a row are separated by commas (or other delimiters like tabs or semicolons).

Example: A file called students.csv might look like this:

RollNo,Name,Marks
1,Aman,85
2,Priya,92
3,Rahul,78

CSV files can be opened in:

  • Any text editor (Notepad, VS Code), Spreadsheet software (Excel, Google Sheets), Python programs using the csv module

The csv Module

Python's built-in csv module provides tools to read from and write to CSV files.

import csv

Writing to a CSV File

Program 1: Basic CSV Writing with csv.writer

import csv

with open("students.csv", "w", newline="") as f:
    writer = csv.writer(f)

    # Write header row
    writer.writerow(["RollNo", "Name", "Marks"])

    # Write data rows
    writer.writerow([1, "Aman", 85])
    writer.writerow([2, "Priya", 92])
    writer.writerow([3, "Rahul", 78])

print("CSV file created successfully!")
CSV file created successfully!

Important: Always use newline="" when opening a CSV file for writing. Without it, you may get extra blank lines between rows on Windows.

Program 2: Writing Multiple Rows at Once with writerows()

import csv

header = ["RollNo", "Name", "Marks"]
data = [
    [1, "Aman", 85],
    [2, "Priya", 92],
    [3, "Rahul", 78],
    [4, "Neha", 88],
    [5, "Vikram", 91]
]

with open("students.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(header)
    writer.writerows(data)

print("CSV file created with", len(data), "records!")
CSV file created with 5 records!

writerows() takes a list of lists and writes each inner list as one row.


Reading from a CSV File

Program 3: Basic CSV Reading with csv.reader

import csv

with open("students.csv", "r") as f:
    reader = csv.reader(f)

    for row in reader:
        print(row)
['RollNo', 'Name', 'Marks']
['1', 'Aman', '85']
['2', 'Priya', '92']
['3', 'Rahul', '78']
['4', 'Neha', '88']
['5', 'Vikram', '91']

Important: csv.reader returns every value as a string. If you need numbers, you must convert them using int() or float().

Program 4: Reading and Skipping the Header

import csv

with open("students.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)  # Skip the header row

    for row in reader:
        roll = int(row[0])
        name = row[1]
        marks = int(row[2])
        print(f"Roll: {roll}, Name: {name}, Marks: {marks}")
Roll: 1, Name: Aman, Marks: 85
Roll: 2, Name: Priya, Marks: 92
Roll: 3, Name: Rahul, Marks: 78
Roll: 4, Name: Neha, Marks: 88
Roll: 5, Name: Vikram, Marks: 91

next(reader) advances the reader by one row, effectively skipping the header.


Using DictWriter and DictReader

These are more readable alternatives that use dictionaries instead of lists.

Program 5: Writing with csv.DictWriter

import csv

header = ["RollNo", "Name", "Marks"]
data = [
    {"RollNo": 1, "Name": "Aman", "Marks": 85},
    {"RollNo": 2, "Name": "Priya", "Marks": 92},
    {"RollNo": 3, "Name": "Rahul", "Marks": 78}
]

with open("students.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writeheader()
    writer.writerows(data)

print("CSV file written using DictWriter!")
CSV file written using DictWriter!

writeheader() writes the field names as the first row. writerows() writes all dictionaries as rows.

Program 6: Reading with csv.DictReader

import csv

with open("students.csv", "r") as f:
    reader = csv.DictReader(f)

    for row in reader:
        print(row["Name"], "-", row["Marks"])
Aman - 85
Priya - 92
Rahul - 78

DictReader automatically uses the first row as keys. Each row is returned as a dictionary, so you can access values by column name instead of index.


Practical Exam Programs

Program 7: Search for a Student by Roll Number

import csv

def search_student(roll_no):
    with open("students.csv", "r") as f:
        reader = csv.reader(f)
        next(reader)  # Skip header

        for row in reader:
            if int(row[0]) == roll_no:
                print("Found:", row[1], "with marks", row[2])
                return

    print("Student with Roll No", roll_no, "not found.")

search_student(2)
search_student(10)
Found: Priya with marks 92
Student with Roll No 10 not found.

Program 8: Count Students Who Scored Above a Threshold

import csv

def count_above(threshold):
    count = 0
    with open("students.csv", "r") as f:
        reader = csv.reader(f)
        next(reader)

        for row in reader:
            if int(row[2]) > threshold:
                count += 1

    print(f"Students scoring above {threshold}: {count}")

count_above(80)
count_above(90)
Students scoring above 80: 4
Students scoring above 90: 2

Program 9: Append a New Record to CSV

import csv

def add_student(roll, name, marks):
    with open("students.csv", "a", newline="") as f:
        writer = csv.writer(f)
        writer.writerow([roll, name, marks])
    print(f"{name} added successfully!")

add_student(6, "Kavya", 87)
add_student(7, "Arjun", 73)
Kavya added successfully!
Arjun added successfully!

Use "a" mode (append) to add records without overwriting existing data.

Program 10: Calculate Average Marks from CSV

import csv

def calculate_average():
    total = 0
    count = 0

    with open("students.csv", "r") as f:
        reader = csv.reader(f)
        next(reader)

        for row in reader:
            total += int(row[2])
            count += 1

    if count > 0:
        print(f"Total students: {count}")
        print(f"Average marks: {total / count:.2f}")
    else:
        print("No records found.")

calculate_average()
Total students: 7
Average marks: 84.86

Program 11: Copy Records with Marks Above 80 to a New File

import csv

with open("students.csv", "r") as infile:
    reader = csv.reader(infile)
    header = next(reader)

    toppers = [row for row in reader if int(row[2]) > 80]

with open("toppers.csv", "w", newline="") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(header)
    writer.writerows(toppers)

print(f"{len(toppers)} toppers written to toppers.csv")
5 toppers written to toppers.csv

Using a Different Delimiter

By default, CSV files use commas. You can specify a different delimiter like tab or pipe.

import csv

# Writing with tab delimiter
with open("data.tsv", "w", newline="") as f:
    writer = csv.writer(f, delimiter="\t")
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Aman", 17, "Delhi"])

# Reading with tab delimiter
with open("data.tsv", "r") as f:
    reader = csv.reader(f, delimiter="\t")
    for row in reader:
        print(row)
['Name', 'Age', 'City']
['Aman', '17', 'Delhi']

Quick Reference: csv Module Methods

Method Description
csv.reader(file) Returns a reader object that iterates over rows as lists
csv.writer(file) Returns a writer object for writing rows
writer.writerow(list) Writes a single row
writer.writerows(list_of_lists) Writes multiple rows
csv.DictReader(file) Returns rows as dictionaries using header as keys
csv.DictWriter(file, fieldnames) Writes dictionaries as rows
dictwriter.writeheader() Writes the header row
next(reader) Skips to the next row (used to skip header)

Key Differences: Text File vs CSV File

Feature Text File CSV File
Structure Unstructured text Tabular (rows and columns)
Separator None (or newlines) Comma (or other delimiter)
Module None needed csv module
Reading read(), readline() csv.reader()
Writing write() csv.writer()
Use case Logs, notes Spreadsheet data, records

Common Exam Questions

Q1: What is the role of newline="" in CSV file handling?

It prevents Python from adding extra blank lines between rows when writing a CSV file on Windows. The csv module handles line endings on its own, so we set newline="" to avoid double newlines.

Q2: What is the difference between writerow() and writerows()?

writerow() writes a single row (one list). writerows() writes multiple rows (a list of lists).

Q3: How does csv.DictReader differ from csv.reader?

csv.reader returns each row as a list, and you access values by index (e.g., row[0]). csv.DictReader returns each row as a dictionary, and you access values by column name (e.g., row["Name"]).

Q4: Write a program to count the number of records in a CSV file.

import csv

with open("students.csv", "r") as f:
    reader = csv.reader(f)
    next(reader)  # Skip header
    count = sum(1 for row in reader)
    print("Number of records:", count)

Tips for the Exam

  1. Always write import csv at the top.
  2. Always use newline="" when opening for writing.
  3. Use next(reader) to skip the header when reading.
  4. Remember that csv.reader returns strings, convert to int or float as needed.
  5. For practical exams, csv.reader and csv.writer are sufficient. DictReader and DictWriter are optional but make code more readable.
  6. Practice the search, count, and append programs, they are the most frequently asked.

CSV file handling is straightforward once you remember the basic pattern: open the file, create a reader or writer, and process the data row by row.

Want to learn more?

Explore free chapter-wise notes with quizzes and code playground

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube