LambdaLabTM
Computer Science · Class 12 · Binary Files
ProgramsBoard pattern⏱️ 20 min read

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.

student.dat — as a list of records
[1, 'Ravi', 78]
[2, 'Meera', 91]
[3, 'Amit', 65]
[4, 'Neha', 88]
The skeleton behind almost all of them
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

📋 The problem

Write a function that takes records from the user and stores them in student.dat, until the user has no more to enter.

create_file.py
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()
Output
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.
Watch Out
'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

📋 The problem

Write a function to read student.dat and display every record, and the number of records.

display_all.py
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()
Output
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

📋 The problem

Write a function that searches student.dat for a given roll number and displays a suitable message if it is not found.

search.py
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)
Output
Found: Meera scored 91
No student with roll number 9
The found flag is worth a mark on its own
“Display a suitable message if not found” is in the question for a reason. Without the flag, searching for roll number 9 prints nothing at all.

5Program 4 — add a record to the file

📋 The problem

Write a function that adds one new record to student.dat without disturbing the records already in it.

append_record.py
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()
Output
Roll number : 4
Name        : Neha
Marks       : 88
Record added.

6Program 5 — update a record

📋 The problem

Write a function that changes the marks of a given roll number in student.dat.

update_record.py
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)
Output
Record updated.
Note
Read them all, change the one you want, write them all back. Trying to write the new record over the old one in place only works while the two take exactly the same number of bytes — the update lesson shows what happens when they do not.

7Program 6 — delete a record

📋 The problem

Write a function that removes the record with a given roll number from student.dat and reports how many were removed.

delete_record.py
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)
Output
Records removed: 1
Deleting is updating with one record missing
Exactly the same three steps. The only difference is that step 2 builds a new list rather than changing one item in the old one.

8Program 7 — count records, and find the highest

📋 The problem

Write a function that displays the students who scored more than 80, counts the records, and reports the highest marks in the file.

count_and_toppers.py
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()
Output
Meera scored 91
Neha scored 88
Records in the file: 4
Highest marks: Meera 91
best = None

There 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

📋 The problem

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:

menu.py
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:

practice.py

11The four patterns behind all eight

Write a record
pickle.dump(record, f)

Programs 1 and 4. 'wb' starts the file again; 'ab' adds to it.

Read every record
try / while True / except EOFError

Programs 2, 3 and 7. The test inside the loop is the only thing that changes.

Remember whether you found it
found = False … if found == False:

Programs 3 and 5. The message belongs after the loop, not inside it.

Read all, change, write all back
records = [...] … open(..., 'wb')

Programs 5 and 6. Update and delete are the same program with a different middle.

✍️ Now write these yourself
  1. 1

    Make book.dat with 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. 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. 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. 4

    Copy the records of students who passed into pass.dat.

    Hint · Two files open at once — one 'rb', one 'wb'.

  5. 5

    Add a “delete” option to the menu program.

    Hint · The function is already written in Program 6.

Quick Check

Which mode does the 'create the file' program use?

Quick Check

A search program prints nothing for a roll number that is not in the file. What is missing?

Quick Check

Update and delete share the same shape. What is it?

Quick Check

Why does best start as None in the highest-marks program?