Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📁 Unit 1 – File Handling  ·  Lesson 08

CSV Files: reader & writer

What is a CSV file?

CSV (Comma-Separated Values) is a plain-text file in which each line is a record and the values (fields) are separated by commas. Spreadsheets like Excel and Google Sheets open and save CSV, so it is the most common way to exchange table data.

RollNameClassMarks
1AshaXII-A91
2RaviXII-B67
3NehaXII-A85
result.csv opened in a spreadsheet
result.csv (as text)
Roll,Name,Class,Marks
1,Asha,XII-A,91
2,Ravi,XII-B,67
3,Neha,XII-A,85

The csv module

✍️
csv.writer(f)Returns a writer object with writerow() and writerows().
📖
csv.reader(f)Returns an iterator; each row is a list of strings.
🗂️
csv.DictReader(f)Each row is a dictionary using the header as keys.
Main tools of the csv module

Writing: writer, writerow, writerows

Python
import csv
rows = [['Roll', 'Name', 'Class', 'Marks'],
        [1, 'Asha', 'XII-A', 91],
        [2, 'Ravi', 'XII-B', 67],
        [3, 'Neha', 'XII-A', 85]]
with open('result.csv', 'w', newline='') as f:
    w = csv.writer(f)
    w.writerow(rows[0])          # header
    w.writerows(rows[1:])        # many rows at once
with open('result.csv') as f:
    print(f.read(), end='')      # it is just text
Roll,Name,Class,Marks 1,Asha,XII-A,91 2,Ravi,XII-B,67 3,Neha,XII-A,85

Why newline=''?

When opening a CSV file for writing, pass newline=''. Otherwise, on Windows, an empty line appears after every row because both Python and the csv module add line endings.

Reading with csv.reader

Python
import csv
with open('result.csv', newline='') as f:
    r = csv.reader(f)
    for row in r:
        print(row)             # every row is a LIST of strings
['Roll', 'Name', 'Class', 'Marks'] ['1', 'Asha', 'XII-A', '91'] ['2', 'Ravi', 'XII-B', '67'] ['3', 'Neha', 'XII-A', '85']

Appending a row

Python
import csv
def add_student():
    with open('result.csv', 'a', newline='') as f:
        csv.writer(f).writerow([4, 'Kabir', 'XII-B', 74])
add_student()
with open('result.csv', newline='') as f:
    data = list(csv.reader(f))
print('Rows (with header):', len(data), '| last:', data[-1])
Rows (with header): 5 | last: ['4', 'Kabir', 'XII-B', '74']

Searching, counting and filtering

Python
import csv
def toppers(limit):
    with open('result.csv', newline='') as f:
        r = csv.reader(f)
        next(r)                      # skip the header row
        count = 0
        for roll, name, cls, marks in r:
            if int(marks) > limit:   # convert text to number
                print(name, marks)
                count += 1
    print('Count:', count)
toppers(80)
Asha 91 Neha 85 Count: 2
Python
import csv
def search(name):
    with open('result.csv', newline='') as f:
        for row in csv.reader(f):
            if row[1].lower() == name.lower():
                return row
    return None
print(search('neha'))
print(search('Zoya'))
['3', 'Neha', 'XII-A', '85'] None
Python
import csv
# copy only XII-B students into a new CSV
with open('result.csv', newline='') as src, open('xiib.csv', 'w', newline='') as dst:
    r = csv.reader(src)
    w = csv.writer(dst)
    w.writerow(next(r))                 # copy header
    for row in r:
        if row[2] == 'XII-B':
            w.writerow(row)
with open('xiib.csv') as f:
    print(f.read(), end='')
Roll,Name,Class,Marks 2,Ravi,XII-B,67 4,Kabir,XII-B,74

DictReader

Python
import csv
def class_average(section):
    total = n = 0
    with open('result.csv', newline='') as f:
        for row in csv.DictReader(f):          # each row is a dict
            if row['Class'] == section:
                total += int(row['Marks'])
                n += 1
    return round(total / n, 2) if n else 0
print('XII-A average:', class_average('XII-A'))
print('XII-B average:', class_average('XII-B'))
XII-A average: 88.0 XII-B average: 70.5

Other delimiters

Python
import csv
with open('items.csv', 'w', newline='') as f:
    w = csv.writer(f, delimiter=';')            # semicolon-separated
    w.writerow(['Item', 'Price'])
    w.writerow(['Pen, blue', 10])              # comma inside value is safe
with open('items.csv') as f:
    print(f.read(), end='')
with open('items.csv', newline='') as f:
    print(list(csv.reader(f, delimiter=';')))
Item;Price Pen, blue;10 [['Item', 'Price'], ['Pen, blue', '10']]

The csv module automatically puts quotes around a value that contains the delimiter, so "Pen, blue" stays one field.

Summary & practice

  • CSV = text table, comma-separated; open with newline=''.
  • Write with csv.writer → writerow / writerows; read with csv.reader (rows are lists of strings).
  • Skip the header with next(reader); convert numbers before maths.
✅ Board-style question

Write ADD() to accept and add [EmpID, Name, Mobile] to record.csv, and COUNTR() to count the number of records in the file (without the header).

Frequently Asked Questions

What is the difference between writerow() and writerows()?
writerow(list) writes one row. writerows(list_of_lists) writes many rows in one call.
Why are numbers read from a CSV file strings?
CSV is a text format, so csv.reader always returns each value as a string. Convert with int() or float() before calculating.
What does newline='' do?
It stops Python from adding an extra blank line between rows on Windows, because the csv module writes its own line endings.
← Class 12 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicStack: PUSH, POP using a List Your progress: 8 / 26 (31%) · Lesson 9 / 26 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free