Binary Files with pickle in Python: Write, Read, Search, Append and Update (Class 12 Computer Science)
Updated 16 October 2026 · Fact-checked
A binary file stores Python objects as bytes. The pickle module writes an object with pickle.dump(obj, file) in 'wb' or 'ab' mode and reads one back with pickle.load(file) in 'rb' mode. Each load returns the next object, and EOFError marks the end, so reading loops use try and except EOFError. Updating means reading, changing and rewriting.
Dump writes an object in wb or ab mode, load reads the next one in rb mode, and EOFError tells you the records have run out.
Illustration drawn for QuestionBuddy.
Understand Binary Files with pickle
A binary file holds bytes rather than readable characters, so it is opened with a b in the mode: rb, rb+, wb, wb+, ab, ab+ (NCERT 2.2.2, 2.8). To store Python objects such as lists and dictionaries in it, Class 12 uses the pickle module (import pickle).
Pickling and unpickling. Converting an object in memory into a stream of bytes is serialisation (pickling); turning the bytes back into the object is de-serialisation (unpickling). In pickle, data is not written and read but dumped and loaded (NCERT 2.8):
pickle.dump(obj, f): writes one object to f, which must be open in a binary write mode (wb, orabto add at the end).obj = pickle.load(f): reads the next object from f, opened inrb. Each call returns exactly what one dump wrote.
Reading every record. If a program dumped records one at a time, the reader does not know how many there are. It keeps loading until load() raises EOFError at the end of the file:
while True:
try:
rec = pickle.load(f)
...
except EOFError:
breakIf the whole list was dumped in one go, a single load returns the whole list.
The four board operations (NCERT 2.8.3, and Q36 in recent sample papers):
- Create/write: open with
wb(erases old data) and dump each record. - Append: open with
ab, take input, dump the new record; old records stay. - Search/display: open with
rb, load until EOFError, print the records that meet the condition, and say so if none was found (use a flag). - Update: read all records into a list, change the ones that match, then open the file in
wband dump every record again. (Changing a loaded copy in memory does not change the file.) The same read-filter-rewrite idea deletes records.
Open files with with or close them, and remember that pickle files are not human-readable: opening one in Notepad shows unreadable bytes.
Binary Files with pickle: key facts
- Binary modes
rb read; file must exist rb+ read and write; file must exist wb write; creates or erases wb+ write and read; creates or erases ab append at the end; creates if missing ab+ append and read - Same meanings as the text modes, with b for binary.
- pickle methods
pickle.dump(obj, f) pickle obj and write it to f obj = pickle.load(f) read and unpickle the next object serialisation (pickling) object → byte stream de-serialisation (unpickling) byte stream → object - The object comes first in dump(); the file is the only argument of load().
- Read-all pattern
- 1.open with rb
- 2.while True:
- 3.try: rec = pickle.load(f)
- 4.process rec
- 5.except EOFError: break
- One load per dump; EOFError means no more objects.
- Update and delete pattern
- 1.load all records into a list
- 2.change (or skip) the matching ones
- 3.open with wb
- 4.dump every record back
- Use a flag to report 'record not found'.
How to answer Binary Files with pickle questions
For a binary file program, decide the operation first, because it fixes the mode and the loop.
- 1import pickle at the top.
- 2Choose the mode: wb to create, ab to append, rb to read or search, rb then wb to update or delete.
- 3To write or append: build the record (usually a list or dictionary, from input() if asked) and call pickle.dump(record, f).
- 4To read: loop with while True, load inside try, and break on EOFError.
- 5To search: test each loaded record and print the matches; set found = True on a match and print a message if found stays False.
- 6To update: collect all records in a list while reading, change the matching fields, then reopen in wb and dump every record.
- 7Close every file (or use with) and call the functions if the question asks.
Binary Files with pickle 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.
Saving a game's state
Suppose a puzzle game stores the player's progress, {'level': 7, 'score': 1350, 'lives': 2}, when the player quits, so the next session can continue.
Write code to save the dictionary to game.dat and load it back. Does the loaded object behave like a dictionary?
Try it first, then show the solutionSolution
- dump() pickles the dictionary into bytes; load() rebuilds the same dictionary.
import pickle state = {'level': 7, 'score': 1350, 'lives': 2} with open('game.dat', 'wb') as f: pickle.dump(state, f) with open('game.dat', 'rb') as f: saved = pickle.load(f) print(saved, saved['level'] + 1)
Answer: {'level': 7, 'score': 1350, 'lives': 2} 8, so the loaded object is a normal dictionary.
Memory hook: Pickling is like pickling mangoes: preserve now, open the jar later and it is the same mango.
Updating a record
Imagine a gym stores members as [id, name, plan] records in gym.dat, and every member on the 'Silver' plan is upgraded to 'Gold'.
Write the update and show the records after it, for M1 Asha Silver, M2 Ravi Gold, M3 Joy Silver.
Try it first, then show the solutionSolution
- Read all records into a list, change the plan where it is 'Silver', then rewrite the file in wb mode.
import pickle with open('gym.dat', 'wb') as f: for r in [['M1', 'Asha', 'Silver'], ['M2', 'Ravi', 'Gold'], ['M3', 'Joy', 'Silver']]: pickle.dump(r, f) recs = [] with open('gym.dat', 'rb') as f: while True: try: r = pickle.load(f) except EOFError: break if r[2] == 'Silver': r[2] = 'Gold' recs.append(r) with open('gym.dat', 'wb') as f: for r in recs: pickle.dump(r, f) with open('gym.dat', 'rb') as f: for i in range(3): print(pickle.load(f))
Answer: ['M1', 'Asha', 'Gold']
['M2', 'Ravi', 'Gold']
['M3', 'Joy', 'Gold']
Memory hook: To update a register you cannot erase: copy it out, correct the copy, write a fresh register.
Tricks to remember Binary Files with pickle
Short memory aids. Say each one aloud once, then use it on a question the same day.
Dump the object into the file
Say it as a sentence: 'dump THIS into THAT': pickle.dump(obj, f).
Use it when: Argument order of dump().
One dump, one load
Every load() returns exactly what one dump() wrote; three dumps need three loads.
Use it when: Output questions on how many objects are read.
EOF is the full stop
EOFError is how the file says 'that's all'; catch it and break.
Use it when: Read-all loops.
Read, fix, rewrite
Updates and deletions follow three verbs: read all, fix in the list, rewrite with wb.
Use it when: 3-mark update functions.
Binary Files with pickle: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: dump() and load() one object · 1 mark · Very short answerBoard level
Write the output:
import pickle
L = [1, 'Geeta', 'F', 26]
f = open('my.dat', 'wb')
pickle.dump(L, f)
f.close()
f = open('my.dat', 'rb')
M = pickle.load(f)
f.close()
print(M, type(M), M == L)Try it first, then show the solutionSolution
- dump() stores the list as bytes; load() rebuilds an equal list.
- The loaded object is a list with the same items.
Answer: [1, 'Geeta', 'F', 26] <class 'list'> True
Example 2: Append and count · 3 marks · Short answerHarder board level
Write add(rec) that appends one record to stu.dat, and count() that returns the number of records in it. Show the result after adding [1, 'Asha', 88], [2, 'Ravi', 64] and [3, 'Joy', 91] to a new file.
Try it first, then show the solutionSolution
- add uses 'ab' so earlier records stay (1 mark); count loads until EOFError (1½ marks); correct calls (½ mark).
import pickle def add(rec): with open('stu.dat', 'ab') as f: pickle.dump(rec, f) def count(): n = 0 with open('stu.dat', 'rb') as f: while True: try: pickle.load(f) n += 1 except EOFError: break return n add([1, 'Asha', 88]) add([2, 'Ravi', 64]) add([3, 'Joy', 91]) print(count())
Answer: 3
Example 3: Search with a flag · 3 marks · Short answerHarder board level
emp.dat holds records [empno, name, salary]: [101, 'Anil', 52000], [102, 'Bina', 47000], [103, 'Charu', 61000]. Write show_high(limit) to display records with salary above limit, or 'No record' if none. Show the calls show_high(50000) and show_high(70000).
Try it first, then show the solutionSolution
- Load until EOFError (1 mark); test r[2] > limit and print (1 mark); the flag and message (1 mark).
import pickle with open('emp.dat', 'wb') as f: for r in [[101, 'Anil', 52000], [102, 'Bina', 47000], [103, 'Charu', 61000]]: pickle.dump(r, f) def show_high(limit): found = False with open('emp.dat', 'rb') as f: while True: try: r = pickle.load(f) except EOFError: break if r[2] > limit: print(r) found = True if not found: print('No record') show_high(50000) show_high(70000)
Answer: [101, 'Anil', 52000]
[103, 'Charu', 61000]
No record
Example 4: Update records · 3 marks · Short answerHarder board level
club.dat holds dictionaries {'id': ..., 'name': ..., 'city': ...}. Write shift(old, new) that changes the city of every member from old to new and reports how many were changed. Use the members {'id': 1, 'name': 'Tara', 'city': 'Pune'}, {'id': 2, 'name': 'Omar', 'city': 'Agra'}, {'id': 3, 'name': 'Liza', 'city': 'Pune'} and call shift('Pune', 'Nagpur').
Try it first, then show the solutionSolution
- Read all records into a list and change the matches (1½ marks); rewrite with wb (1 mark); report (½ mark).
import pickle with open('club.dat', 'wb') as f: for d in [{'id': 1, 'name': 'Tara', 'city': 'Pune'}, {'id': 2, 'name': 'Omar', 'city': 'Agra'}, {'id': 3, 'name': 'Liza', 'city': 'Pune'}]: pickle.dump(d, f) def shift(old, new): recs, n = [], 0 with open('club.dat', 'rb') as f: while True: try: d = pickle.load(f) except EOFError: break if d['city'] == old: d['city'] = new n += 1 recs.append(d) with open('club.dat', 'wb') as f: for d in recs: pickle.dump(d, f) print(n, 'updated') shift('Pune', 'Nagpur') with open('club.dat', 'rb') as f: print(pickle.load(f)['city'], pickle.load(f)['city'], pickle.load(f)['city'])
Answer: 2 updated
Nagpur Agra Nagpur
Example 5: One dump of a list versus many dumps · 2 marks · Short answerHOTS / competency
Predict the output:
import pickle
with open('a.dat', 'wb') as f:
pickle.dump([10, 20, 30], f)
with open('b.dat', 'wb') as f:
for x in [10, 20, 30]:
pickle.dump(x, f)
for name in ['a.dat', 'b.dat']:
n = 0
with open(name, 'rb') as f:
while True:
try:
obj = pickle.load(f)
n += 1
except EOFError:
break
print(name, n, obj)Try it first, then show the solutionSolution
- a.dat holds one object, the whole list: one load, and obj is [10, 20, 30]. (1 mark)
- b.dat holds three objects: three loads, and obj is the last one, 30. (1 mark)
Answer: a.dat 1 [10, 20, 30]
b.dat 3 30
Example 6: Case study: course enrolments (5 marks) · 5 marks · Long answerHOTS / competency
Suppose a coaching centre keeps enrolments as [roll, name, course, fee] in enrol.dat.
(i) Write add_enrol() that takes one enrolment from the user and appends it. (2 marks)
(ii) Write raise_fee(course, fee) that sets the fee of every student of that course and displays the updated records. (3 marks)
Show the run where the file already holds [1, 'Asha', 'AI', 40000] and [2, 'Ravi', 'Web', 30000], the user enters 3, Joy, AI, 40000, and raise_fee('AI', 45000) is called.
Try it first, then show the solutionSolution
- (i) Read the fields with input(), convert numbers with int(), and dump in 'ab' mode.
- (ii) Read all, change r[3] when r[2] == course, rewrite with 'wb', then display.
import pickle with open('enrol.dat', 'wb') as f: pickle.dump([1, 'Asha', 'AI', 40000], f) pickle.dump([2, 'Ravi', 'Web', 30000], f) def add_enrol(): r = int(input('Roll: ')) n = input('Name: ') c = input('Course: ') fee = int(input('Fee: ')) with open('enrol.dat', 'ab') as f: pickle.dump([r, n, c, fee], f) def raise_fee(course, fee): recs = [] with open('enrol.dat', 'rb') as f: while True: try: rec = pickle.load(f) except EOFError: break if rec[2] == course: rec[3] = fee recs.append(rec) with open('enrol.dat', 'wb') as f: for rec in recs: pickle.dump(rec, f) print(rec) add_enrol() print() raise_fee('AI', 45000) - Marks: input and conversion (1), dump in ab (1); reading till EOFError (1), condition and change (1), rewrite and display (1).
Answer: Roll: 3
Name: Joy
Course: AI
Fee: 40000
[1, 'Asha', 'AI', 45000]
[2, 'Ravi', 'Web', 30000]
[3, 'Joy', 'AI', 45000]
Where students lose marks in Binary Files with pickle
The slips examiners see most often, and what to write instead.
Mistake: Reversing the arguments of dump()
dump() takes the object first and the file second.
Wrong working
pickle.dump(f, rec)
Right working
pickle.dump(rec, f)
Do this: Say 'dump this into that'.
Usually costs: Half to 1 mark.
Mistake: Reading with a for loop or a fixed count
The number of records is unknown; load() signals the end with EOFError.
Wrong working
for rec in f:
print(rec)Right working
while True:
try:
rec = pickle.load(f)
except EOFError:
break
print(rec)Do this: Use the while True / try / except EOFError pattern.
Usually costs: 1 mark.
Mistake: Changing a loaded record but not rewriting the file
load() gives a copy in memory; the file changes only when you dump again.
Do this: Collect all records in a list, change them, then open in 'wb' and dump each one.
Usually costs: 1-2 marks in an update question.
Mistake: Opening a binary file in text mode
pickle works with bytes; dump() to a file opened with 'w' raises TypeError.
Wrong working
f = open('stu.dat', 'w')
pickle.dump(rec, f)Right working
f = open('stu.dat', 'wb')
pickle.dump(rec, f)Do this: Always add b: rb, wb, ab.
Usually costs: Half a mark.
Exam tips
- The 5-mark Section E question in recent sample papers is a binary-file pair: input and append a record (2 marks), then update records that match a condition (3 marks). Practise both halves until they take under 10 minutes.
- Write import pickle once at the top of your answer; it is part of the marking.
- Take numbers with int(input()) so comparisons such as fee > 50000 work.
- In search questions, the 'not found' message earns a mark; use a found flag.
- Use the field positions given in the question (r[0], r[2] ...) or dictionary keys exactly as named.
Practice questions on Binary Files with pickle
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 module is used to write Python objects to a binary file?
(a) csv (b) pickle (c) math (d) randomHint
Preserve now, open later.
Answer
(b) pickle
Q2 · 1 mark · Very short answerBoard level
Which mode opens a binary file to add records at the end, keeping the old ones?
Hint
a for append, b for binary.
Answer
'ab'
Q3 · 1 mark · Very short answerBoard level
Write the correct statement to pickle the dictionary D into the file object f.
Hint
Dump this into that.
Answer
pickle.dump(D, f)
Q4 · 1 mark · Very short answerHarder board level
Predict the output:
import pickle with open('x.dat', 'wb') as f: pickle.dump('red', f) pickle.dump([1, 2], f) pickle.dump({'k': 9}, f) with open('x.dat', 'rb') as f: a = pickle.load(f) b = pickle.load(f) print(a, b)Hint
One load per dump, in order.
Answer
red [1, 2]
Q5 · 3 marks · Short answerHarder board level
stu.dat holds records [roll, name, marks]: [1, 'Asha', 88], [2, 'Ravi', 64], [3, 'Joy', 91]. Write delete_roll(r) that removes the record with roll r and prints the number of records left. Show delete_roll(2).
Hint
Read, keep the others, rewrite.
Answer
import pickle with open('stu.dat', 'wb') as f: for rec in [[1, 'Asha', 88], [2, 'Ravi', 64], [3, 'Joy', 91]]: pickle.dump(rec, f) def delete_roll(r): keep = [] with open('stu.dat', 'rb') as f: while True: try: rec = pickle.load(f) except EOFError: break if rec[0] != r: keep.append(rec) with open('stu.dat', 'wb') as f: for rec in keep: pickle.dump(rec, f) print(len(keep), 'records left') delete_roll(2)Output: 2 records left
Q6 · 1 mark · Assertion-reasonHarder board level
Assertion (A): A loop that reads all the records of a binary file with pickle.load() should handle EOFError.
Reason (R): pickle.load() raises EOFError when there are no more objects to read.
(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
How does the loop know it has finished?
Answer
(a) Both are true and R explains A.
Q7 · 2 marks · Short answerHOTS / competency
A student adds a fourth record to stu.dat (which holds 3 records) with this code. How many records does the file hold afterwards, and why?
import pickle with open('stu.dat', 'wb') as f: pickle.dump([4, 'Mona', 77], f)Hint
What does wb do to an existing file?
Answer
Only 1. 'wb' erases the file before writing, so the three old records are lost; 'ab' should be used to append.
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 is pickling?Show answer
Converting a Python object into a byte stream (serialisation) to store it in a binary file.
2.Which exception marks the end of a pickle file while loading?Show answer
EOFError.
3.In which mode must a file be opened for pickle.load()?Show answer
A binary read mode, 'rb' (or 'rb+').
4.What does pickle.load(f) return?Show answer
The next object that was dumped into the file.
5.How is a record updated in a binary file?Show answer
Read all records into a list, change the matching ones, and rewrite the file in 'wb' mode.
6.What happens if a binary file is opened in 'wb' mode?Show answer
It is created, or its old contents are erased.
Binary Files with pickle: frequently asked questions
What is the difference between a text file and a binary file?
A text file stores readable characters arranged in lines. A binary file stores bytes, here produced by pickle, which are not meant to be read in a text editor; it is opened with modes such as rb, wb and ab.
Why do we use try-except EOFError while reading a binary file?
pickle.load() reads one object at a time and raises EOFError when no object is left. Catching it lets the loop stop cleanly after the last record.
How do I update a record in a binary file in Class 12?
Load every record into a list, change the fields of the matching records, then open the file in wb mode and dump all the records back. NCERT 2.8.3 covers these file operations.
Can I store a dictionary in a binary file?
Yes. pickle can store any Python object, including lists, tuples and dictionaries; load() gives back the same kind of object.