Binary File Practice Programs
Every binary-file question the board asks is one of six jobs — create, display, search, append, update, delete — on a file of records. Here they are, written the way the paper wants them: as functions, each doing one job.
1The file every program uses
student.dat holds four records, each a list of roll number, name, marks. Every output on this page was produced by running the program against it.
[1, 'Ravi', 78]
[2, 'Meera', 91]
[3, 'Amit', 65]
[4, 'Neha', 88]import pickle, open the file in the right mode, then try / while True / except EOFError with your test inside the loop, close the file, print the answer. Learn that shape and six of the eight programs below are already written.2Program 1 — create the file
Write a function that takes records from the user and stores them in student.dat, until the user has no more to enter.
import pickle
def create_file():
f = open('student.dat', 'wb')
more = 'y'
while more == 'y':
roll = int(input('Roll number : '))
name = input('Name : ')
marks = int(input('Marks : '))
pickle.dump([roll, name, marks], f)
more = input('One more (y/n)? ')
f.close()
print('File created.')
create_file()Roll number : 1 Name : Ravi Marks : 78 One more (y/n)? y Roll number : 2 Name : Meera Marks : 91 One more (y/n)? n File created.
'wb' means this program starts the file again every time it runs. That is right for a “create” function and wrong for anything else — Program 4 is the one that adds.3Program 2 — display all the records
Write a function to read student.dat and display every record, and the number of records.
import pickle
def display_all():
f = open('student.dat', 'rb')
total = 0
try:
while True:
record = pickle.load(f)
print(record[0], record[1], record[2])
total = total + 1
except EOFError:
pass
f.close()
print('Records read:', total)
display_all()1 Ravi 78 2 Meera 91 3 Amit 65 4 Neha 88 Records read: 4
while True:Nothing in the file says how many records it holds, so the loop has no condition of its own.
except EOFError:The end of the file arrives as an exception. This is the normal way the loop finishes, not a fault.
f.close()Outside the try, so it runs after the exception has been handled.
4Program 3 — search for a record
Write a function that searches student.dat for a given roll number and displays a suitable message if it is not found.
import pickle
def search(roll):
f = open('student.dat', 'rb')
found = False
try:
while True:
record = pickle.load(f)
if record[0] == roll:
print('Found:', record[1], 'scored', record[2])
found = True
break
except EOFError:
pass
f.close()
if found == False:
print('No student with roll number', roll)
search(2)
search(9)Found: Meera scored 91 No student with roll number 9
5Program 4 — add a record to the file
Write a function that adds one new record to student.dat without disturbing the records already in it.
import pickle
def append_record():
roll = int(input('Roll number : '))
name = input('Name : ')
marks = int(input('Marks : '))
f = open('student.dat', 'ab')
pickle.dump([roll, name, marks], f)
f.close()
print('Record added.')
append_record()Roll number : 4 Name : Neha Marks : 88 Record added.
6Program 5 — update a record
Write a function that changes the marks of a given roll number in student.dat.
import pickle
def update_record(roll, new_marks):
f = open('student.dat', 'rb')
records = []
try:
while True:
records.append(pickle.load(f))
except EOFError:
pass
f.close()
found = False
for r in records:
if r[0] == roll:
r[2] = new_marks
found = True
f = open('student.dat', 'wb')
for r in records:
pickle.dump(r, f)
f.close()
if found == True:
print('Record updated.')
else:
print('No record with roll number', roll)
update_record(3, 72)Record updated.
7Program 6 — delete a record
Write a function that removes the record with a given roll number from student.dat and reports how many were removed.
import pickle
def delete_record(roll):
f = open('student.dat', 'rb')
records = []
try:
while True:
records.append(pickle.load(f))
except EOFError:
pass
f.close()
kept = []
removed = 0
for r in records:
if r[0] == roll:
removed = removed + 1
else:
kept.append(r)
f = open('student.dat', 'wb')
for r in kept:
pickle.dump(r, f)
f.close()
print('Records removed:', removed)
delete_record(2)Records removed: 1
8Program 7 — count records, and find the highest
Write a function that displays the students who scored more than 80, counts the records, and reports the highest marks in the file.
import pickle
def count_and_toppers():
f = open('student.dat', 'rb')
total = 0
best = None
try:
while True:
record = pickle.load(f)
total = total + 1
if record[2] > 80:
print(record[1], 'scored', record[2])
if best == None or record[2] > best[2]:
best = record
except EOFError:
pass
f.close()
print('Records in the file:', total)
print('Highest marks:', best[1], best[2])
count_and_toppers()Meera scored 91 Neha scored 88 Records in the file: 4 Highest marks: Meera 91
best = NoneThere is no 'first record' to start from until one has been read, so the running best starts empty.
if best == None or record[2] > best[2]:The first half handles the first record; the second half is the ordinary comparison. Python stops at the first half when it is True, so best[2] is never read while best is None.
9Program 8 — putting them together
Write a menu-driven program that offers the operations above.
A board question sometimes asks for the whole thing. The functions do not change — only the menu around them is new:
import pickle
def display_all():
f = open('student.dat', 'rb')
try:
while True:
print(pickle.load(f))
except EOFError:
pass
f.close()
def append_record():
roll = int(input('Roll number : '))
name = input('Name : ')
marks = int(input('Marks : '))
f = open('student.dat', 'ab')
pickle.dump([roll, name, marks], f)
f.close()
choice = 0
while choice != 3:
print()
print('1. Display all records')
print('2. Add a record')
print('3. Quit')
choice = int(input('Your choice: '))
if choice == 1:
display_all()
elif choice == 2:
append_record()
elif choice == 3:
print('Bye.')
else:
print('Please choose 1, 2 or 3.')10Run one yourself
This program creates the file and then runs three of the jobs on it. Change the roll numbers, or add a program of your own at the bottom:
11The four patterns behind all eight
pickle.dump(record, f)Programs 1 and 4. 'wb' starts the file again; 'ab' adds to it.
try / while True / except EOFErrorPrograms 2, 3 and 7. The test inside the loop is the only thing that changes.
found = False … if found == False:Programs 3 and 5. The message belongs after the loop, not inside it.
records = [...] … open(..., 'wb')Programs 5 and 6. Update and delete are the same program with a different middle.
- 1
Make
book.datwith book number, title and price, then display every book costing more than 300.Hint · float(input(...)) for the price, and the reading loop with an if.
- 2
Count how many students scored below the class average.
Hint · Two passes: one to total the marks, one to compare. Or read into a list once.
- 3
Increase every student's marks by 5 and write the file back.
Hint · Read all, change every record, write all back. No if needed.
- 4
Copy the records of students who passed into pass.dat.
Hint · Two files open at once — one
'rb', one'wb'. - 5
Add a “delete” option to the menu program.
Hint · The function is already written in Program 6.
Which mode does the 'create the file' program use?
A search program prints nothing for a roll number that is not in the file. What is missing?
Update and delete share the same shape. What is it?
Why does best start as None in the highest-marks program?