Append records to a binary file and display students who scored above 75
Expt. No.13
Page No.26
Binary file: append and filter
Aim
To write a Python program that appends student records to a binary file and displays the students who scored above 75.
Concepts used
Algorithm
- add_records(): open result.dat in "ab" mode and write each new [roll, name, marks] record.
- show_above(limit): read every record until EOFError and display it if its marks are above the limit.
Program
# Binary file: append records and show students above 75 import pickle def add_records(): n = int(input("How many records to add? ")) with open("result.dat", "ab") as f: for i in range(n): roll = int(input("Roll number: ")) name = input("Name : ") marks = int(input("Marks : ")) pickle.dump([roll, name, marks], f) def show_above(limit): print("Students with marks above", limit, ":") with open("result.dat", "rb") as f: try: while True: rec = pickle.load(f) if rec[2] > limit: print(rec[0], rec[1], rec[2]) except EOFError: pass add_records()show_above(75)
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python binary_file_append.py
How many records to add? 4
Roll number: 4
Name : Diya
Marks : 92
Roll number: 5
Name : Ishaan
Marks : 70
Roll number: 6
Name : Kavya
Marks : 81
Roll number: 7
Name : Neel
Marks : 59
Students with marks above 75 :
4 Diya 92
6 Kavya 81
✓ Printed by running this program, not typed by hand.
Result
Four records were appended to result.dat, and Diya (92) and Kavya (81) were displayed as the students above 75.
Viva voce: what the examiner may ask
01What does "ab" mode do if the file does not exist?
It creates a new empty file and writes to it.
02Why does the reading loop not need to know how many records there are?
It keeps loading until pickle.load() raises EOFError at the end of the file.
03Can a text file be opened in "ab" mode?
The mode can be used, but writing strings in binary mode needs bytes; for text you use "a".
Variations for the lab test
- Display the average marks of all students.
- Copy the students above 75 into a new binary file.
- Count how many students scored below 33.
! Common mistake Opening the file in "wb" mode erases all earlier records each time records are added.