On this page
File handling questions in CBSE Class 12 computer science are long, often four or five marks, and they follow a small set of patterns: count something in a text file, search or update records in a binary file, or append to and total a CSV file. This post covers each kind of file with code that has been run and checked, then the common mistakes and a practice routine.
What does the syllabus say about files?
The CBSE Computer Science curriculum for Class XII (2026-27) lists three file types. Text files: open modes r, r+, w, w+, a and a+, opening with the with clause, write() and writelines(), read(), readline() and readlines(), and seek and tell. Binary files: modes rb, rb+, wb, wb+, ab and ab+, the pickle module's dump() and load(), and read, write, search, append and update operations. CSV files: the csv module, writer(), writerow(), writerows() and reader().
The NCERT chapter on file handling, 2026-27 reprint, covers text files and the pickle module, but it has no section on the csv module. For that part, the Python csv documentation is the reference.
How do you read and write a text file?
with open("notes.txt", "w") as f:
f.write("Physics is fun\n")
f.writelines(["Maths is logic\n", "Python is a tool\n"])
with open("notes.txt", "a") as f:
f.write("Chemistry is everywhere\n")Mode w creates the file or empties an existing one; mode a adds to the end. The documentation for open() lists r as "open for reading (default)", w as "open for writing, truncating the file first" and a as "open for writing, appending to the end of file if it exists". The with clause closes the file for you.
Reading:
read() returns the whole file as one string.
readline() returns one line, with its \n at the end, and an empty string at the end of the file.
readlines() returns a list of the remaining lines.
The Python tutorial on file methods adds that tell() returns the file's current position and seek(offset) moves it. After the first readline() on notes.txt, tell() prints 15 on this plain-text file, the length of "Physics is fun" plus its newline. seek(0) goes back to the start.
Board-style task. Count the lines that start with "P".
count = 0
with open("notes.txt") as f:
for line in f:
if line.startswith("P"):
count += 1
print(count) # 2How do you store records in a binary file with pickle?
A binary file can hold Python objects such as lists. pickle.dump(obj, f) writes one object; pickle.load(f) reads the next one. To read every record, keep loading until the file ends, which raises EOFError.
import pickle
def add_record(roll, name, marks):
with open("students.dat", "ab") as f:
pickle.dump([roll, name, marks], f)
def read_all():
records = []
with open("students.dat", "rb") as f:
try:
while True:
records.append(pickle.load(f))
except EOFError:
pass
return recordsUpdating a record. Read all records, change the one you want, then write them all back in wb mode.
def update_marks(roll, new_marks):
records = read_all()
found = False
for rec in records:
if rec[0] == roll:
rec[2] = new_marks
found = True
with open("students.dat", "wb") as f:
for rec in records:
pickle.dump(rec, f)
return foundAfter add_record(1, "Asha", 78) and add_record(2, "Ravi", 64), update_marks(2, 70) returns True and the file holds [1, 'Asha', 78] and [2, 'Ravi', 70]. The pickle documentation carries a warning worth knowing outside the exam: "The pickle module is not secure. Only unpickle data you trust."
How do you use the csv module?
import csv
with open("marks.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["Roll", "Name", "Marks"])
w.writerows([[1, "Asha", 78], [2, "Ravi", 64], [3, "Meera", 91]])
total = 0
with open("marks.csv", "r", newline="") as f:
r = csv.reader(f)
next(r) # skip the header row
for row in r:
total += int(row[2])
print(total) # 233Two details from the csv documentation: a file used with the csv module "should be opened with newline=''", and each row read "is returned as a list of strings", with no automatic conversion. That is why the code uses int(row[2]); without it, adding "78" to a number raises a TypeError.
The CBSE sample question paper for 2026-27 has one question of each kind: the difference between seek() and tell(), a four-mark CSV question that appends rows and totals a calculated column, and a five-mark binary file question that appends records and updates a field.
What mistakes cost marks?
Opening in w when you meant a, which wipes the existing file.
Using rb on a file that does not exist. Read modes do not create files; Python raises FileNotFoundError.
No EOFError handling in a pickle loop.
Forgetting int() or float() on values read from a CSV file.
Not skipping the header row before totalling.
Mixing modes, such as calling pickle.dump on a file opened in text mode.
A practice routine for file handling
Day 1: Text files. Write functions that count vowels, count words and copy lines without the letter "a" into a new file. All three are on the curriculum's practical list.
Day 2: Binary files. Write add, display, search by roll number and update.
Day 3: CSV files. Write add and search, as in the practical task of storing user IDs and passwords and searching for one.
Weekly: One long file question from a sample paper, written by hand, then typed and run.
For the rest of the programming unit, see the Python basics that are tested and our guide to stacks in Python.
If the difference between text and binary data is still unclear, the Fermi Concept Library has every concept in computing with its own lesson, so you can understand what a file stores before writing the code.
Write add_record and read_all from memory today, run them, and print what the file holds.



