★★★★★
"The one step solution for my son. Modern Age Coders make learning coding so simple that kids love it. The teachers explain complex concepts clearly with practical exercises and interactive content."
Ria Mukherjee
Parent
CBSE Class 12 · Computer Science, code 083 · pickle and csv
Binary file handling in class 12 looks like a lot of programs. It is really one loop, written four times with a different line inside. This page builds that loop once, uses it to search, append and update, does the same for CSV, and then solves four and five-mark questions with the half marks shown beside each part.
Live one to one · 4 and 5-mark programs solved · output printed from real runs · class times set by you
Start here
The first course is the board syllabus itself. The second strengthens ordinary Python. The third follows the records into a database, which is where the project usually goes.

XI and XII / Board course
File handling, the stack and Python to MySQL connectivity are its Class 12 core, with the report file and project running beside them.
Open the course →
Python / Data in files
Covers CSV writing, saved data and errors in practice, then puts them to work in projects that keep their records between runs.
Open the course →
MySQL / Records at scale
Search, update and append become SELECT, UPDATE and INSERT. A good second step once the file versions make sense.
Open the course →Ans. The short version
Binary file handling in Class 12 Computer Science (CBSE 083) uses the pickle module: dump() writes a Python object to a file opened in wb or ab, and load() reads one object back from a file opened in rb, until EOFError marks the end. The syllabus asks for read, write, search, append and update. CSV files use csv.writer() and csv.reader(). In the 2026-27 sample paper the two carry nine marks in Questions 33 and 36. Modern Age Coders teaches both live, personalised one to one at your own timing, and a priority demo comes first if you wish.
Q1. Three file types, one decision
A binary file stores data as bytes in the form Python keeps it, so a list comes back as a list. A text file stores characters, and a CSV file is a text file whose lines are rows with values separated by commas.
| Point | Text file | Binary file | CSV file |
|---|---|---|---|
| Module to import | none | pickle | csv |
| Writes with | write(), writelines() | pickle.dump(object, file) | writerow(), writerows() |
| Reads with | read(), readline(), readlines() | pickle.load(file) | csv.reader(file) |
| A mark of 88 comes back as | the string '88' | the integer 88 | the string '88' |
| The end shows itself as | an empty string | EOFError | the for loop simply stops |
| Opens readably in Notepad | yes | no | yes, and in a spreadsheet |
| Mode | load() straight away | dump() of a new record | File missing? |
|---|---|---|---|
rb | returns the record | refused | FileNotFoundError |
rb+ | returns the record | replaces the bytes at the start | FileNotFoundError |
wb | refused | only the new record remains | created |
wb+ | EOFError, it was just emptied | only the new record remains | created |
ab | refused | added after the old record | created |
ab+ | EOFError, pointer is at the end | added after the old record | created |
Forget the b, and Python complains at once: dumping into a file opened in w gives TypeError: write() argument must be str, not bytes. Assertion and reason items like these two tables; the official Question 20 asks about rb.
Q2. How many loads does it take?
Each dump() writes one object and each load() reads one object. To read a file of unknown length, call load() inside an endless loop and let EOFError end it.
import pickle
def create_file():
"""Store each bus pass with its own dump."""
passes = [[101, "Zoya", "R5", 3],
[102, "Imran", "R2", 1],
[103, "Leela", "R5", 6]]
with open("pass.dat", "wb") as f:
for record in passes:
pickle.dump(record, f)
print(len(passes), "records written")
create_file()3 records written
A record here is pass number, name, route and months left.
import pickle
def show_all():
"""Display every record in pass.dat."""
with open("pass.dat", "rb") as f:
try:
while True:
record = pickle.load(f)
print(record)
except EOFError:
print("No more records")
show_all()[101, 'Zoya', 'R5', 3] [102, 'Imran', 'R2', 1] [103, 'Leela', 'R5', 6] No more records
The try is outside the while, so the fourth load leaves the loop. With try inside and pass in the except, the loop would never stop.
| One dump per record | One dump of a list of records | |
|---|---|---|
| Write | pickle.dump(record, f) in a loop | pickle.dump(passes, f) once |
| Read | load() until EOFError | one load(), then loop over the list |
| Append | open in ab and dump | load the list, append to it, dump all in wb |
| Official answer, Question 36 | this way |
import pickle
with open("team.dat", "wb") as f:
pickle.dump([["Asha", 4], ["Bela", 7]], f)
with open("team.dat", "ab") as f:
pickle.dump(["Chand", 9], f)
with open("team.dat", "rb") as f:
team = pickle.load(f)
print(len(team), team)2 [['Asha', 4], ['Bela', 7]]
Chand is in the file, as a second object. One load never reaches him.
The exam usually tells you the shape of a record. If it does not say how records are stored, use one dump per record and write that in a comment. The flow of try and except is explained on exception handling for Class 12.
Q3. Search, append, update
Search reads until the record matches. Append opens in ab and dumps. Update reads every record into a list, changes the ones that match and writes the whole list back.
import pickle
def find_pass(number):
"""Display the pass with this number."""
found = False
with open("pass.dat", "rb") as f:
try:
while not found:
record = pickle.load(f)
if record[0] == number:
print(record[1], "on route", record[2])
found = True
except EOFError:
print("Pass", number, "not found")
find_pass(103)
find_pass(110)Leela on route R5 Pass 110 not found
A pass number is unique, so the loop stops at the first match. To find everyone on R5 you must read to the end.
import pickle
def add_pass():
"""Accept one record and add it at the end."""
number = int(input("Pass number: "))
name = input("Name: ")
route = input("Route: ")
months = int(input("Months: "))
with open("pass.dat", "ab") as f:
pickle.dump([number, name, route, months], f)
print("Saved")
add_pass()Pass number: 104 Name: Tenzin Route: R2 Months: 2 Saved
Convert before dumping. If 104 is stored as a string, find_pass(104) will not find it.
import pickle
def extend_route(route, extra):
"""Add extra months to every pass on a route."""
records = []
changed = 0
with open("pass.dat", "rb") as f:
try:
while True:
record = pickle.load(f)
if record[2] == route:
record[3] += extra
changed += 1
records.append(record)
except EOFError:
pass
with open("pass.dat", "wb") as f:
for record in records:
pickle.dump(record, f)
return changed
print("Passes changed:", extend_route("R5", 2))Passes changed: 2
| Load | Record | Route R5? | Goes into records as |
|---|---|---|---|
| 1 | 101 Zoya | yes | [101, Zoya, R5, 5] |
| 2 | 102 Imran | no | unchanged |
| 3 | 103 Leela | yes | [103, Leela, R5, 8] |
| 4 | 104 Tenzin | no | unchanged |
| 5 | none | EOFError | loop ends, file rewritten |
The indent that matters: records.append(record) lines up with the if, not inside it. One level deeper and Imran and Tenzin vanish from the file, with no error to warn you.
import pickle
def change_route(number, new_route):
"""Overwrite one record of the same length."""
with open("pass.dat", "rb+") as f:
try:
while True:
position = f.tell() # before the load
record = pickle.load(f)
if record[0] == number:
record[2] = new_route
f.seek(position)
pickle.dump(record, f)
print("Route changed")
break
except EOFError:
print("Not found")
change_route(102, "R7")Route changed
Only when the new record takes exactly as many bytes as the old one. R2 and R7 are both two letters, so it worked.
We then tried it with a name made longer, Zoya to Zoya Khan. The new record ran into the next one, and the following load failed with UnpicklingError. With a shorter name, the leftover bytes broke it in the same way.
So in the exam, choose the rewrite. It is the method in the official answer to Question 36, and it has no length condition to forget.
The 083 list for binary files is read, write, search, append and update. Deleting is not named. If a teacher asks, it is the update program with one change: append the record to the list only when it should stay.
Functions that return a count, as ours do, are covered in functions for Class 12.
Q4. reader, writer and the strings between them
Open the file, make a writer or reader object from it, and work with rows as lists. Every value you read is a string, whatever it was when you wrote it.
import csv
rows = [["Meenu", "Wheat", 40, 2400],
["Rao, Anita", "Cotton", 12, 7000],
["Harpal", "Wheat", 55, 2350]]
with open("harvest.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Farmer", "Crop", "Quintals", "Rate"])
writer.writerows(rows)
with open("harvest.csv", "r") as f:
print(f.read())Farmer,Crop,Quintals,Rate Meenu,Wheat,40,2400 "Rao, Anita",Cotton,12,7000 Harpal,Wheat,55,2350
A value that contains a comma is wrapped in quotes by the writer, and the reader takes them off again.
import csv
def crop_value(crop):
"""Return the total value of one crop."""
total = 0
with open("harvest.csv", "r", newline="") as f:
reader = csv.reader(f)
next(reader) # header row
for row in reader:
if row[1] == crop:
total += int(row[2]) * int(row[3])
return total
print("Wheat:", crop_value("Wheat"))
print("Jute:", crop_value("Jute"))Wheat: 225250 Jute: 0
40 x 2400 is 96000 and 55 x 2350 is 129250. Leave out next() and nothing fails here, since no crop is called Crop, but a program that converts every row would stop with ValueError at "Quintals".
import csv
def new_rate(crop, rate):
"""Change the rate of a crop in harvest.csv."""
with open("harvest.csv", "r", newline="") as f:
rows = list(csv.reader(f))
changed = 0
for row in rows[1:]:
if row[1] == crop:
row[3] = rate
changed += 1
with open("harvest.csv", "w", newline="") as f:
csv.writer(f).writerows(rows)
print(changed, "rows changed")
new_rate("Wheat", 2500)
with open("harvest.csv", "r") as f:
print(f.read())2 rows changed Farmer,Crop,Quintals,Rate Meenu,Wheat,40,2500 "Rao, Anita",Cotton,12,7000 Harpal,Wheat,55,2500
The slice rows[1:] skips the heading while changing, and rows, with the heading, is what gets written.
| Call | Result |
|---|---|
writerow([["p", 1], ["q", 2]]) | One row of two list texts. Use writerows |
writerows(["ab", "cd"]) | Rows a,b and c,d |
writerow(5) | Error: iterable expected, not int |
writerow(["x", None, 2.5]) | x,,2.5, None becomes an empty value |
"9" > "85" on values read back | True, because strings are compared letter by letter |
The csv writer ends each row with its own line ending. On Windows, a file opened without newline="" adds a second one, and the reader then gives an empty list after every row:
[['a', '1'], [], ['b', '2'], []]
The first row[1] on an empty list raises IndexError. The official answer leaves it out and still earns its marks, so use it as protection in the lab.
Q5. Full answers with half marks
A four-mark CSV question has two functions of two marks each; the five-mark binary question has a two-mark append and a three-mark search or update. Try each on paper, then compare.
A rescue zoo keeps Animals.csv with TagNo, Species and Weight, and no heading row. Write (I) add_animal() to accept one animal and append it; (II) heavy(limit) to display the tag and species of animals heavier than the limit, and return how many there are.
import csv
def add_animal():
"""Append one animal typed by the user."""
tag = input("Tag: ")
species = input("Species: ")
weight = float(input("Weight in kg: "))
with open("Animals.csv", "a", newline="") as f:
csv.writer(f).writerow([tag, species, weight])
def heavy(limit):
"""Show animals above limit kg, return the count."""
count = 0
with open("Animals.csv", "r", newline="") as f:
for row in csv.reader(f):
if float(row[2]) > limit:
print(row[0], row[1])
count += 1
return count
for turn in range(3):
add_animal()
print("Count:", heavy(90))Tag: Z1 Species: Sloth bear Weight in kg: 104.5 Tag: Z2 Species: Otter Weight in kg: 9 Tag: Z3 Species: Leopard Weight in kg: 92 Z1 Sloth bear Z3 Leopard Count: 2
Without float(), row[2] > limit would compare a string with a number and raise TypeError.
| Part | Half mark for each |
|---|---|
| I | input, append mode, writer object, writerow |
| II | read mode, reader object, condition with conversion, display and return |
Fines.csv has the columns Member, Days, Paid (Y or N) and a heading row. Write (I) copy_unpaid() to copy the heading and the unpaid rows to Due.csv; (II) due_total() to return the money due in Due.csv at 2 rupees a day.
Member,Days,Paid Kiran,12,N Sofia,5,Y Arjun,8,N
import csv
def copy_unpaid():
"""Copy heading and unpaid rows to Due.csv."""
with open("Fines.csv", "r", newline="") as fin, \
open("Due.csv", "w", newline="") as fout:
writer = csv.writer(fout)
for row in csv.reader(fin):
if row[2] != "Y":
writer.writerow(row)
def due_total():
"""Return the amount due at 2 a day."""
days = 0
with open("Due.csv", "r", newline="") as f:
reader = csv.reader(f)
next(reader)
for row in reader:
days += int(row[1])
return days * 2
copy_unpaid()
print("Due:", due_total())Due: 40
Testing for "not Y" lets the heading through without a separate line. Kiran 12 and Arjun 8 make 20 days.
A blood bank stores dictionaries with the keys donor, group and units in Blood.dat. Write functions to (I) input a record and append it; (II) display the donors of a given group and the total units, or a message if there are none.
import pickle
def add_donor():
"""Append one donor record."""
record = {}
record["donor"] = input("Donor: ")
record["group"] = input("Group: ")
record["units"] = int(input("Units: "))
with open("Blood.dat", "ab") as f:
pickle.dump(record, f)
def group_total(group):
"""Display donors of a group and total units."""
total = 0
with open("Blood.dat", "rb") as f:
try:
while True:
record = pickle.load(f)
if record["group"] == group:
print(record["donor"])
total += record["units"]
except EOFError:
pass
if total == 0:
print("No donor of group", group)
else:
print("Units of", group, "=", total)
for turn in range(3):
add_donor()
group_total("O+")
group_total("AB-")Donor: Faiz Group: O+ Units: 2 Donor: Nisha Group: B+ Units: 1 Donor: Joel Group: O+ Units: 1 Faiz Joel Units of O+ = 3 No donor of group AB-
| Part | Marks |
|---|---|
| I: header, append mode, input, dump() | ½ each |
| II: header | ½ |
| II: opening in rb | ½ |
| II: load() in a loop with try and except | 1 |
| II: condition and total | 1 |
Shows.dat holds lists of ShowID, Title, Seats and Price. Write functions to (I) write a list of shows to the file, one record at a time; (II) raise the Price by 10 percent for shows with fewer than 50 seats left, and display how many prices changed.
import pickle
def write_shows(shows):
"""Create Shows.dat, one dump per show."""
with open("Shows.dat", "wb") as f:
for show in shows:
pickle.dump(show, f)
def raise_price():
"""Add 10 percent where seats are below 50."""
kept = []
changed = 0
with open("Shows.dat", "rb") as f:
try:
while True:
show = pickle.load(f)
if show[2] < 50:
show[3] = show[3] * 110 // 100
changed += 1
kept.append(show)
except EOFError:
pass
write_shows(kept)
print("Prices changed:", changed)
write_shows([["S1", "Ankuran", 35, 200],
["S2", "Tamasha", 80, 150],
["S3", "Rang", 12, 250]])
raise_price()
with open("Shows.dat", "rb") as f:
for turn in range(3):
print(pickle.load(f))Prices changed: 2 ['S1', 'Ankuran', 35, 220] ['S2', 'Tamasha', 80, 150] ['S3', 'Rang', 12, 275]
Part II reuses the function of part I to write the file back. Whole-number arithmetic keeps the price an integer.
Programs for the report file, with the roll number search and the marks update the syllabus lists, are in the practical file guide. To write one of these inside a three-hour paper, use our 70-mark sample paper.
Q6. Short questions
These are the one and two-mark versions: modes, methods, types and one line that is wrong.
dump() stores it and load() reads it back.pickle.dump(f, rec) or pickle.dump(rec, f)? pickle.dump(rec, f): the object first, then the file.ab+. Move the pointer with seek(0) before reading.writerow() and writerows(). w.writerow([1, "Ana"]); w.writerows([[1, "Ana"], [2, "Bo"]]).len(list(csv.reader(f))) - 1, provided no blank rows were written.list(reader) give when it is called a second time on the same reader? wb before it was read, or the records were never appended to the list. Read and close first, then write.with open("a.dat", "r") as f: rec = pickle.load(f). rb. In text mode load() raises TypeError, since it needs bytes.A class often opens with the eight-line reading loop on a blank page. When it comes without thinking, the long questions shrink.
Programs are run with no match, two matches, an empty file and a name with a comma in it.
Each part of your answer is ticked against the step it earns, and the missing step is written in by you.
If modes and pointers still feel uncertain, go back to text file handling. If they are clear, try the case study questions and the MCQ test.
One to one, at your own timing
A five-mark program is learnt by writing it, having it corrected and writing it again. That needs a teacher who is looking at your page only, so the classes are personalised one to one and you decide the days and the clock time. A priority demo is the way to judge this first: you pay for one full class, and that fee is adjusted in month one if you enrol. Prefer a lighter look? Take the free demo class. Monthly billing, no admission fee, and any month end can be your last.
Before you enrol · Try a class
a full live class of about 45 to 60 minutes
The classes · Choose your own timing
₹4,999
per month, 4 private classes, fully flexible timingtwo private classes a week, at a time set with you
How long the chapter takes depends on how sure your loops and lists are. After the demo you get a plan in plain steps, not a fixed package. You see the monthly fee in your own currency on this page.
Studying outside India?
If your CBSE school is in Bahrain, Nepal or Malaysia, Question 33 and Question 36 are waiting for you too. Tell us the hours your family keeps and the class goes there.
| Where you live | Time difference | Usual class window, local time | Format |
|---|---|---|---|
| India every Indian city | Indian time | Any time you choose | Personalised 1-on-1 |
| UAE and Oman Dubai, Abu Dhabi, Sharjah, Muscat | 1 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Saudi Arabia, Qatar, Kuwait, Bahrain Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama | 2 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Nepal Kathmandu | 15 min ahead of India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Ethiopia and East Africa Addis Ababa and East Africa Time | 2 h 30 min behind India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Singapore and Malaysia Singapore, Kuala Lumpur | 2 h 30 min ahead of India | 3:30 PM to 9:00 PM | Personalised 1-on-1 |
Python on your own computer is enough: pickle and csv come with it. If you use a school laptop that blocks installs, mention it when you book.
What families say
Real reviews from real families. We neither write nor commission them.
★★★★★
"The one step solution for my son. Modern Age Coders make learning coding so simple that kids love it. The teachers explain complex concepts clearly with practical exercises and interactive content."
Ria Mukherjee
Parent
★★★★★
"Modern Age Coders has been a game-changer for me. I struggled to grasp IT concepts and coding before joining, but their classes transformed everything. I can now confidently write complex programs with ease."
Samriddha Mondal
Student
★★★★★
"One of the most wonderful education centres out there. Education is not limited to school syllabus but focuses on skill development."
Vansh Agarwal
Student
★★★★★
"My child Dhairya is really enjoying the Modern Age Coders classes. This is his first online class and he eagerly looks forward to it. I can already see his improvement, and the teachers are very cooperative."
Sonam Oswal
Parent of Dhairya
★★★★★
"Modern Age Coders have wonderful teachers who teach in a clear, easy and practical way. The teacher boosts students' confidence and inspires them to learn without hesitation."
Sonu Goyal
Parent
★★★★★
"I highly recommend this computer coding class! The teachers are incredibly knowledgeable and passionate about coding."
Ritu Kedia
Parent
The rest of the Class 12 series
Every page in the CBSE Class 12 Computer Science series, grouped by what you need.
CBSE Class 12 Informatics Practices (065): Class 12 IP practical file Class 12 IP project with source code Class 12 IP sample paper practice Class 12 IP important questions
CBSE Class 12 Information Technology (802): IT 802 practical and project file IT 802 Java notes and programs IT 802 notes
CBSE Class 11 CS, IP and AI: Class 11 CS practical file Class 11 IP practical file CS or IP in Class 11
ISC Computer Science (868): ISC Class 12 CS syllabus 2027 ISC Class 12 CS practice paper ISC Class 12 practical questions solved ISC Boolean algebra and K-maps
Program lists with output: Class 12 CS practical file 20 Python programs for Class 12 Menu-driven programs in Python
Questions about binary and CSV files
It is storing Python objects such as lists and dictionaries as bytes, using the pickle module. The CBSE 083 syllabus for 2026-27 lists the modes rb, rb+, wb, wb+, ab and ab+, the dump() and load() methods, and the operations read, write, search, append and update.
pickle is a Python module that turns an object into bytes and back. pickle.dump(obj, f) writes the object to a binary file that is open for writing, and pickle.load(f) returns the next object from a file open for reading. A list comes back as a list, with its numbers still numbers.
Because load() has no other way to say that the file is over. It raises EOFError when nothing is left to read. Putting the reading loop inside try, with except EOFError, ends the loop cleanly. It also handles a file that is completely empty.
Read every record into a list, change the records that match, close the file, then open it in wb and dump all the records again. The alternative is rb+ with tell() and seek(), but it is only safe when the changed record has the same length in bytes.
Read all records, keep in a list only those that should stay, and write that list back in wb mode. Deleting is not named among the binary file operations of the 2026-27 syllabus, so treat it as extra practice on the update pattern.
A CSV file is a text file with a rule: each line is a record and the values are separated by commas. You read it with csv.reader(), which splits every line into a list of strings, and write it with csv.writer(), which adds commas and puts quotes around values that contain a comma.
On Windows, the file was opened without newline="". The csv writer already ends each row, and text mode changes that ending again. Write open("data.csv", "w", newline=""), and the blank rows stop. Old files with blank rows can be read by skipping rows whose length is 0.
In the 2026-27 sample paper, Question 33 is a four-mark CSV program and Question 36 is a five-mark binary file program, with no internal choice in either. Question 20 adds one mark on the rb mode. CBSE does not promise the same split in the actual paper.
The 2026-27 marking scheme says the import may be ignored in Questions 33 and 36 as part of the complete program. Write it anyway. It takes one line, and in the practical the program will not run without it.
Use what the question says. If it gives only field names, either will do; the official answer uses a list. A list is shorter to write, and you must remember which index holds what. A dictionary is longer but reads clearly: record["units"] needs no explanation.
Yes. The classes are one to one and monthly, so the first weeks can be spent on files alone. Start with a priority demo, a full live class with a written skill report and its fee adjusted in the first month if you enrol, or with a free demo class.
Start
Come to the free demo class with a binary or CSV question you could not finish. The teacher will not finish it for you: you get the next step, then the one after it, until it runs.
With a priority demo you fix the slot and have a full class: an append function, an update function, both tested and marked, and a skill report in writing to keep. If you go on to enrol, the demo fee is adjusted against your first month.
The whole paper is mapped on exam date, pattern and marks.
WhatsApp us · +91 91233 66161 · connect@modernagecoders.com
Every class is live video. The form requests a callback and reserves nothing.
A full live class of about 45 to 60 minutes at a slot you pick, with a written skill report and learning roadmap on WhatsApp afterwards. The fee is adjusted against your first month if you enrol.
Book a priority demo