Free Study Material

CSV File Handling

Introduction

Spreadsheets, gradebooks, and databases all need a simple way to exchange tabular data with other programs — rows and columns of values. CSV (Comma Separated Values) is that format: a plain text file where each line is one row, and commas separate the columns within it. You already know how to open, read, and write a plain text file — CSV is still a text file, just with one extra rule about how commas divide each line into columns, and Python has a dedicated csv module built specifically to handle that rule correctly.

Concept

You could, in theory, read a CSV file as plain text and split each line on commas yourself — but real-world CSV data is full of edge cases (values that contain commas, quotes, blank lines) that a naive .split(",") gets wrong. The csv module exists so you never have to handle those edge cases by hand.

csv.reader(file) wraps an already-open file and gives you an iterator: loop over it, and each row comes back as a list of strings — one element per column — never as one giant unsplit line.

Worked Example

import csv

with open("data.csv", "w") as f:
    f.write("Name,Roll,Score\n")
    f.write("Amit,1,90\n")
    f.write("Sumit,2,85\n")

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

Each print(row) shows a list — ['Name', 'Roll', 'Score'], then ['Amit', '1', '90'] — never a raw comma-joined string.

Note: Every value csv.reader() gives you is a string, even numbers like "90" — you'll need int()/float() yourself if you want to do arithmetic on a column.

Summary

CSV is a plain-text, row-per-line, comma-separated format for tabular data. csv.reader(file) is the correct way to read it in Python — it hands back each row as a ready-to-use list of strings, avoiding the edge cases a manual .split(",") would get wrong.

The "Universal" Format

CSV stands for Comma Separated Values. It is the language of spreadsheets.

To Python, a CSV file looks like a normal text file. But to the csv module, it looks like a table. The module automatically splits the commas so you don't have to.

import csv  # Mandatory Import

How to Read

We use the csv.reader() function. It creates an object that you can loop through (iterate) to get each row.

Step 1: Open the file (usually in 'r' mode).
Step 2: Pass the file object to csv.reader().
Step 3: Loop through the reader.
import csv

# 1. Create a dummy CSV file first
with open("data.csv", "w") as f:
    f.write("Name,Roll,Score\n")
    f.write("Amit,1,90\n")
    f.write("Sumit,2,85\n")

# 2. Read it back
print("Reading CSV File...")

with open("data.csv", "r") as f:
    # Create the reader object
    data_reader = csv.reader(f)
    
    # Loop through it
    for row in data_reader:
        # Notice: Each row is a LIST of strings
        print(row)

Introduction

writerow() writes one row — a single list — as one line of a CSV file, while writerows() writes many rows at once from a list of lists, one line per row. Both are methods of the writer object returned by csv.writer(), the mirror image of csv.reader(), and both need the file opened with newline='' so that no extra blank lines appear between rows.

Concept

  • writer.writerow(row) writes a single row — one list, one line.
  • writer.writerows(rows) writes many rows at once — a list of lists, one line each.

Both automatically handle the tricky formatting csv.reader() protects you from on the way in: if a value itself contains a comma (like an address "12, MG Road"), csv.writer() automatically wraps it in quotes so it isn't mistaken for two separate columns.

Explanation

There's one setup detail that matters every time you write a CSV file: open it with newline=''. Without it, Windows can insert an extra blank line after every row, because both Python's own text mode and the csv module try to handle line endings, and end up doing it twice.

Worked Example

import csv

data = [
    ["Name", "Address", "Role"],
    ["Amit", "12, MG Road", "Admin"],
    ["Priya", "Sector 4", "User"]
]

with open("special_chars.csv", "w", newline='') as f:
    cw = csv.writer(f)
    cw.writerows(data)

Open the resulting file and "12, MG Road" appears as "12, MG Road" — quoted automatically, so it's still read back as one single value, not two.

Warning: Forgetting newline='' when opening a CSV file for writing is one of the most common CSV bugs — the file still "works", but gains a blank line between every row.

Summary

writerow() writes one row; writerows() writes many at once — both are always safer than hand-building comma-joined strings, since they correctly quote values that contain commas. Always open a CSV file for writing with newline=''.

Why not just use `f.write()`?

You might wonder: "Why can't I just create a string like 'Amit,90' and write it?"

You could, but it's dangerous. What if the student's name is "Smith, John"? The comma inside the name would break your columns!

The csv.writer() object acts as a smart Translator. It handles:

  • Delimiters: Automatically putting commas between items.
  • Quoting: If data contains a comma (e.g., "Delhi, India"), the writer wraps it in quotes automatically so Excel understands it's one cell.
  • Line Endings: Managing how new rows are started.

The "Blank Line" Problem

This is the #1 mistake students make in Board Exams.

The Issue: On Windows, Python converts \n (newline) into \r\n (Carriage Return + Newline). The CSV module also adds its own newline.
The Result: Double newlines! Your Excel file looks like it has a blank row between every single record.

The Fix: We must tell Python's file opener to "Stop translating newlines." We do this by adding newline=''.

# CORRECT WAY
with open("data.csv", "w", newline='') as f:
    cw = csv.writer(f)

Single vs. Batch Writing

Method Input Type Best Used For...
writerow() A Single List
['A', 'B']
Writing one record at a time inside a loop (e.g., taking user input).
writerows() A List of Lists
[ ['A'], ['B'] ]
Dumping a whole database or existing list to the file instantly.
import csv

data = [
    ["Name", "Address", "Role"],
    ["Amit", "12, MG Road", "Admin"],  # Note the comma in address!
    ["Priya", "Sector 4", "User"]
]

# 1. Open with newline=''
with open("special_chars.csv", "w", newline='') as f:
    cw = csv.writer(f)
    
    # 2. Dump all data
    cw.writerows(data)

print("File created. Open it to see how '12, MG Road' is handled!")
# In the file, it will look like: Amit,"12, MG Road",Admin

Introduction

You now have everything needed to build a real, file-backed data tool in Python — the same shape as a small gradebook, contact list, or inventory tracker.

Concept

- Read: csv.reader(file) — each row comes back as a list of strings. - Write one row: writer.writerow(row). - Write many rows: writer.writerows(rows). - Always open a CSV file for writing with newline='', and append new rows with mode "a" rather than "w" so existing records survive.

Explanation

Combining these with a while True menu loop — the same pattern you've used for interactive programs all year — turns simple read/write operations into a real, usable mini-application that keeps running until the user chooses to exit.

Worked Example

import csv

filename = "gradebook.csv"

def add_student():
    name = input("Enter Name: ")
    marks = input("Enter Marks: ")
    with open(filename, "a", newline='') as f:
        cw = csv.writer(f)
        cw.writerow([name, marks])

def view_students():
    try:
        with open(filename, "r") as f:
            cr = csv.reader(f)
            for row in cr:
                if len(row) > 0:
                    print(row[0], row[1])
    except FileNotFoundError:
        print("No records found. Add a student first!")
Tip: view_students() wraps its file-read in try/except FileNotFoundError — a program that tries to view a gradebook before anyone has added a student shouldn't crash, it should say so.

Summary

A complete CSV-backed program combines csv.reader()/csv.writer() with a menu loop and basic error handling — exactly the pattern the full practice program below builds out into a working gradebook manager.

The CSV Toolkit

You now know how to bridge the gap between Python and Excel. Here is your quick reference guide for the Board Exam.

CSV Functions Cheat Sheet

Function Syntax Use Case & Example
import import csv Must be the first line.
Enables all CSV tools.
open (Write) open("f.csv", "w", newline='') Prevents blank lines.
Essential for Windows users.
writer() obj = csv.writer(file) Creates the "pen" to write data.
writerow() obj.writerow([a, b]) Writes ONE row.
Ex: obj.writerow(["Amit", 90])
writerows() obj.writerows(nested_list) Writes MULTIPLE rows.
Ex: obj.writerows([[a,b], [c,d]])
reader() obj = csv.reader(file) Creates the "scanner" to read data.
You loop through this object.
import csv

filename = "gradebook.csv"

# --- FUNCTION 1: Add a new student ---
def add_student():
    print("\n--- Add New Student ---")
    name = input("Enter Name: ")
    marks = input("Enter Marks: ")
    
    # Open in APPEND mode ('a') to keep old data
    # newline='' is crucial here!
    with open(filename, "a", newline='') as f:
        cw = csv.writer(f)
        cw.writerow([name, marks]) 
    print("Student Saved Successfully!")

# --- FUNCTION 2: View all students ---
def view_students():
    print("\n--- Class Report ---")
    try:
        with open(filename, "r") as f:
            cr = csv.reader(f)
            
            # Print a header for neatness
            print(f"{'Name':<15} {'Marks':<5}")
            print("-" * 25)
            
            for row in cr:
                # row is a list like ['Amit', '90']
                # We use existing data, if empty row, skip
                if len(row) > 0:
                    print(f"{row[0]:<15} {row[1]:<5}")
                    
    except FileNotFoundError:
        print("No records found. Add a student first!")

# --- MAIN MENU LOOP ---
while True:
    print("\n=== KV Gradebook Manager ===")
    print("1. Add Student")
    print("2. View All")
    print("3. Exit")
    
    choice = input("Enter Choice (1-3): ")
    
    if choice == '1':
        add_student()
    elif choice == '2':
        view_students()
    elif choice == '3':
        print("Goodbye!")
        break
    else:
        print("Invalid Choice. Try again.")

Want the full course?

Unlock all chapters, video lectures, and SQL practice exercises.

Get Full Access