CSV Files with the csv Module: writer(), writerow(), writerows() and reader() (Class 12 Computer Science)
Updated 16 October 2026 · Fact-checked
A CSV file is a text file in which each line is a record and commas separate the fields. After import csv, csv.writer(f) gives an object whose writerow(list) writes one record and writerows(list_of_lists) writes many. csv.reader(f) returns each record as a list of strings, so numbers must be converted with int() or float().
Writer turns a list into one comma-separated line; reader gives back strings, so convert fields like row[2] with int() before using them as numbers.
Illustration drawn for QuestionBuddy.
Understand CSV Files with the csv Module
CSV (comma-separated values) is a plain-text format for tables: each line is one record and the fields in it are separated by commas, for example 2,Ravi,64. Spreadsheets and databases can import and export it, which is why it is in the CBSE syllabus (the NCERT chapter does not cover it; the syllabus names writer(), writerow(), writerows() and reader()).
Opening. A CSV file is opened like a text file, with modes 'r', 'w' or 'a'. Pass newline='' when opening it for the csv module; without it, on Windows each record written is followed by an extra blank line, because the writer already ends rows with its own line ending. Close the file, or use with.
Writing.
import csv
f = open('marks.csv', 'w', newline='')
w = csv.writer(f)
w.writerow(['Roll', 'Name', 'Marks']) # one record
w.writerows([[1, 'Asha', 88], [2, 'Ravi', 64]]) # many records
f.close()writerow() takes one sequence (list or tuple) and writes its items separated by commas. writerows() takes a sequence of such sequences. Numbers are written as text automatically. If a field itself contains a comma, the writer puts it in double quotes, e.g. "Delhi, India", so it stays one field. Because a string is also a sequence, writerow('abc') writes a,b,c: always pass a list.
Reading. csv.reader(f) gives an object you loop over: each record comes as a list of strings. So row[2] is '88', not 88; convert with int(row[2]) before arithmetic or numeric comparison (comparing strings, '9' > '10' is True). The first row is often a header; skip it with next(r) (a built-in that takes the next row) or by checking the row.
Board pattern (Q33 in recent sample papers, 4 marks): one function that takes a record from the user and appends it (mode 'a', writerow), and one that reads the file and computes something: a total, a count of records meeting a condition, or a display of matching records.
CSV Files with the csv Module: key facts
- csv functions in the syllabus
csv.writer(f) returns a writer object for file f writer.writerow(seq) writes one record writer.writerows(seq_of_seqs) writes several records csv.reader(f) returns a reader that gives each record as a list of strings - DictReader and DictWriter are not in the syllabus.
- Opening a CSV file
open('f.csv', 'w', newline='') create or overwrite open('f.csv', 'a', newline='') add records at the end open('f.csv', 'r', newline='') read - newline='' prevents blank lines between records on Windows.
- Types when reading
- every field is a string → int(row[i]) or float(row[i]) for numbers
- '9' > '10' is True for strings; convert before comparing.
- Skipping the header
- 1.r = csv.reader(f)
- 2.next(r)
- 3.for row in r: ...
- Or test if row[0] == 'Roll': continue.
How to answer CSV Files with the csv Module questions
Use this plan for CSV programs.
- 1Write import csv at the top.
- 2To add a record: take each field with input() (int() for numbers), open in 'a' with newline='', make w = csv.writer(f) and call w.writerow([...]).
- 3To create a file with many records: open in 'w' and call writerows() with a list of lists.
- 4To read: open in 'r', r = csv.reader(f), skip the header if there is one, then loop for row in r.
- 5Pick fields by position (row[0], row[1] ...) and convert numbers before arithmetic.
- 6Accumulate totals or counts in variables set to 0 before the loop; print or return them after it.
- 7Close the file or use with, and call the functions if asked.
CSV Files with the csv Module in real life
The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Appending and totalling records
Suppose a school library keeps fines in fines.csv with fields MemberID, Book, DaysLate, FinePerDay, and already has two rows: M101, Python Basics, 3, 5 and M102, World Atlas, 6, 5.
Write AddFine(rec) to append a record and TotalFine() to return the total fine (DaysLate × FinePerDay summed). Add M103, Space Facts, 2, 10 and find the total.
Try it first, then show the solutionSolution
- Append with mode 'a' and writerow; read with reader and convert fields 2 and 3 to int.
import csv def AddFine(rec): with open('fines.csv', 'a', newline='') as f: csv.writer(f).writerow(rec) def TotalFine(): total = 0 with open('fines.csv', 'r', newline='') as f: for row in csv.reader(f): total += int(row[2]) * int(row[3]) return total AddFine(['M103', 'Space Facts', 2, 10]) print(TotalFine())- 15 + 30 + 20 = 65.
Answer: 65
Memory hook: a for add, int() before you add up.
A comma inside a field
Imagine an exporter writing addresses such as 'Delhi, India' into a CSV that a spreadsheet will open.
Show how the csv writer stores the record ['Asha', 'Delhi, India', 17] and what the reader gives back.
Try it first, then show the solutionSolution
- The writer quotes a field that contains a comma, so the comma is not taken as a separator.
import csv with open('addr.csv', 'w', newline='') as f: csv.writer(f).writerow(['Asha', 'Delhi, India', 17]) with open('addr.csv') as f: print(f.read(), end='') with open('addr.csv', newline='') as f: for row in csv.reader(f): print(row, len(row))
Answer: Asha,"Delhi, India",17
['Asha', 'Delhi, India', '17'] 3
Memory hook: Quotes are a fence: commas inside the fence do not split the field.
Tricks to remember CSV Files with the csv Module
Short memory aids. Say each one aloud once, then use it on a question the same day.
row = one, rows = many
writerow takes one list; writerows takes a list of lists.
Use it when: Choosing the method.
Everything comes back as text
The reader hands you strings only; int() is your translator.
Use it when: Arithmetic on CSV data.
newline='' = no gaps
Empty newline, no empty lines.
Use it when: Opening a file for the csv writer.
next() steps over the heading
The header is the doorman: next(r) walks past him to the records.
Use it when: Files with a header row.
CSV Files with the csv Module: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: What reader() returns · 1 mark · Very short answerBoard level
marks.csv contains:
Roll,Name,Marks
1,Asha,88
2,Ravi,64
3,Joy,91
4,Mona,72
Write the output:
import csv
with open('marks.csv', newline='') as f:
r = csv.reader(f)
print(next(r))
print(next(r))Try it first, then show the solutionSolution
- The first next() returns the header row as a list of strings.
- The second returns the first record; 88 comes back as the string '88'.
Answer: ['Roll', 'Name', 'Marks']
['1', 'Asha', '88']
Example 2: Writing a file and reading it back · 2 marks · Short answerHarder board level
Write code to create items.csv with the header Code,Item,Price and the records [11, 'Pen', 10] and [12, 'Ink', 45], using writerow() for the header and writerows() for the records. Then print the file as plain text and the number of lines.
Try it first, then show the solutionSolution
- writer() on a file opened with 'w' and newline='' (½ mark); writerow and writerows (1 mark); read back (½ mark).
import csv with open('items.csv', 'w', newline='') as f: w = csv.writer(f) w.writerow(['Code', 'Item', 'Price']) w.writerows([[11, 'Pen', 10], [12, 'Ink', 45]]) with open('items.csv') as f: lines = f.readlines() print(''.join(lines), end='') print(len(lines))
Answer: Code,Item,Price
11,Pen,10
12,Ink,45
3
Example 3: Counting with a condition · 3 marks · Short answerHarder board level
Using marks.csv above, write count_above(m) that skips the header and returns how many students scored more than m. Show count_above(75).
Try it first, then show the solutionSolution
- Open and create the reader (1 mark); skip the header with next() and loop (1 mark); convert and count (1 mark).
import csv def count_above(m): c = 0 with open('marks.csv', 'r', newline='') as f: r = csv.reader(f) next(r) for row in r: if int(row[2]) > m: c += 1 return c print(count_above(75))- Asha 88 and Joy 91 qualify.
Answer: 2
Example 4: Append from input and display the topper · 4 marks · Long answerHarder board level
Write add_student() that takes Roll, Name and Marks from the user and appends them to marks.csv, and topper() that displays the name and marks of the highest scorer. Show the run when the user enters 5, Kiran, 95.
Try it first, then show the solutionSolution
- add_student: input with int() for numbers, open in 'a', writerow (2 marks).
- topper: read, skip the header, keep the best row by comparing int(row[2]) (2 marks).
import csv def add_student(): roll = int(input('Roll: ')) name = input('Name: ') marks = int(input('Marks: ')) with open('marks.csv', 'a', newline='') as f: csv.writer(f).writerow([roll, name, marks]) def topper(): best = None with open('marks.csv', newline='') as f: r = csv.reader(f) next(r) for row in r: if best is None or int(row[2]) > int(best[2]): best = row print(best[1], best[2]) add_student() print() topper()
Answer: Roll: 5
Name: Kiran
Marks: 95
Kiran 95
Example 5: Comparing without converting · 2 marks · Short answerHOTS / competency
Predict the output and explain the second line:
import csv
with open('m.csv', 'w', newline='') as f:
csv.writer(f).writerows([['A', 9], ['B', 10]])
with open('m.csv', newline='') as f:
rows = list(csv.reader(f))
print(rows)
print(rows[0][1] > rows[1][1], int(rows[0][1]) > int(rows[1][1]))Try it first, then show the solutionSolution
- The numbers come back as strings: [['A', '9'], ['B', '10']]. (1 mark)
- As strings, '9' > '10' is True because '9' > '1' at the first character; as integers 9 > 10 is False. (1 mark)
Answer: [['A', '9'], ['B', '10']]
True False
Example 6: Case study: a sports-day register · 4 marks · Case-basedHOTS / competency
Suppose a PE teacher records events in sports.csv as Name, House, Points. The file has: Asha, Red, 10; Ravi, Blue, 6; Joy, Red, 8; Mona, Green, 10.
(i) Write the statement that creates the writer object for an open file f. (1 mark)
(ii) Write house_points() that returns a dictionary of total points per house. (2 marks)
(iii) The teacher's file opened in Excel shows a blank row after every record. What was missed? (1 mark)
Try it first, then show the solutionSolution
- (i) w = csv.writer(f)
- (ii)
import csv with open('sports.csv', 'w', newline='') as f: csv.writer(f).writerows([['Asha', 'Red', 10], ['Ravi', 'Blue', 6], ['Joy', 'Red', 8], ['Mona', 'Green', 10]]) def house_points(): tot = {} with open('sports.csv', newline='') as f: for name, house, pts in csv.reader(f): tot[house] = tot.get(house, 0) + int(pts) return tot print(house_points()) - (iii) newline='' was not given when opening the file for writing, so on Windows each row got an extra line ending.
Answer: (i) w = csv.writer(f) (ii) {'Red': 18, 'Blue': 6, 'Green': 10} (iii) newline='' in open()
Where students lose marks in CSV Files with the csv Module
The slips examiners see most often, and what to write instead.
Mistake: Doing arithmetic on fields without int()
Fields are strings, so + joins them and comparisons go character by character.
Wrong working
total += row[2] # TypeError for an int total
Right working
total += int(row[2])
Do this: Convert every numeric field when you read it.
Usually costs: 1 mark.
Mistake: Passing several arguments to writerow()
writerow() takes one sequence, not separate values.
Wrong working
w.writerow(roll, name, marks)
Right working
w.writerow([roll, name, marks])
Do this: Put the fields in square brackets.
Usually costs: Half to 1 mark.
Mistake: Using 'w' to add a record
'w' erases the existing records.
Wrong working
open('marks.csv', 'w', newline='') # to add one student
Right working
open('marks.csv', 'a', newline='')
Do this: Append with 'a'.
Usually costs: 1 mark.
Mistake: Counting the header as a record
The first row holds column names, not data, and int('Marks') raises ValueError.
Do this: Skip it with next(r) before the loop when the file has a header.
Usually costs: Half to 1 mark.
Exam tips
- The 4-mark CSV question in recent sample papers pairs an 'accept and append' function with a 'read and calculate' function; write both with with open(..., newline='').
- Copy the field order from the question; reading row[2] when the question lists marks third is the most common slip.
- State in one line that reader() returns lists of strings if asked to explain your int() calls.
- If the question does not mention a header row, do not skip the first record.
- Stick to writer(), writerow(), writerows() and reader(); the syllabus does not include DictReader or DictWriter.
Practice questions on CSV Files with the csv Module
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
Which method of a csv writer object writes a single record?
(a) write() (b) writerow() (c) writerows() (d) writeline()Hint
row = one.
Answer
(b) writerow()
Q2 · 1 mark · Very short answerBoard level
Name the module that must be imported to use reader() and writer() for CSV files.
Hint
Same as the file type.
Answer
csv
Q3 · 1 mark · MCQBoard level
In what form does csv.reader() give each record?
(a) a string (b) a tuple of numbers (c) a list of strings (d) a dictionaryHint
Everything comes back as text.
Answer
(c) a list of strings
Q4 · 2 marks · Short answerHarder board level
Predict the output:
import csv with open('t.csv', 'w', newline='') as f: w = csv.writer(f) w.writerows([[1, 2], [3, 4], [5, 6]]) w.writerow([7, 8]) with open('t.csv', newline='') as f: data = list(csv.reader(f)) print(len(data), data[-1])Hint
Count the records, then look at the last one's type.
Answer
4 ['7', '8']
Q5 · 3 marks · Short answerHarder board level
Using marks.csv (Roll, Name, Marks with a header row), write show_range(lo, hi) that displays the names of students whose marks are from lo to hi inclusive. Show show_range(60, 80) for the four records 1 Asha 88, 2 Ravi 64, 3 Joy 91, 4 Mona 72.
Hint
Skip the header; lo <= m <= hi.
Answer
import csv def show_range(lo, hi): with open('marks.csv', newline='') as f: r = csv.reader(f) next(r) for row in r: if lo <= int(row[2]) <= hi: print(row[1]) show_range(60, 80)Output: Ravi, Mona (one per line)
Q6 · 1 mark · Assertion-reasonHarder board level
Assertion (A): Values read with csv.reader() must be converted before arithmetic.
Reason (R): csv.reader() returns every field as a string.
(a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (c) A is true but R is false. (d) A is false but R is true.Hint
What is '88' + 1?
Answer
(a) Both are true and R explains A.
Q7 · 2 marks · Short answerHOTS / competency
What is written to the file by this code, and why?
import csv with open('w.csv', 'w', newline='') as f: csv.writer(f).writerow('abc') with open('w.csv') as f: print(f.read(), end='')Hint
Is a string a sequence?
Answer
a,b,c. writerow() treats its argument as a sequence of fields, and a string is a sequence of characters; pass ['abc'] to write one field.
Test your recall
Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.
1.What does CSV stand for?Show answer
Comma-separated values.
2.Which function creates a writer object?Show answer
csv.writer(file_object).
3.What is the difference between writerow() and writerows()?Show answer
writerow() writes one record; writerows() writes many records from a list of lists.
4.Why is newline='' used when opening a CSV file?Show answer
To stop blank lines appearing between records on Windows.
5.How do you skip the header row while reading?Show answer
Call next(r) on the reader before the loop.
6.What happens to a field containing a comma when written?Show answer
The writer encloses it in double quotes.
CSV Files with the csv Module: frequently asked questions
What is the difference between writerow() and writerows()?
writerow() writes a single record from one list or tuple. writerows() writes several records from a list of lists (or similar), one record per line.
Why do I get blank lines between rows in my CSV file?
The file was opened without newline=''. The csv writer ends each row itself, and on Windows the text layer adds another line ending. Open with open('f.csv', 'w', newline='').
Is CSV in the NCERT Class 12 Computer Science book?
No. CSV files are in the CBSE 2026-27 syllabus (import csv, open/close, writer(), writerow(), writerows(), reader()) but the NCERT chapter covers only text and binary files, so learn it from the syllabus list and sample papers.
Why does reader() give numbers as strings?
A CSV file is plain text, so every field is read as text. Convert with int() or float() before calculations.