Create a binary file with roll number, name and marks and update the marks of a student
Expt. No.12
Page No.24
Binary file: update marks
Aim
To write a Python program that creates a binary file with roll number, name and marks, then updates the marks for a roll number entered by the user.
Concepts used
Algorithm
- create_file(): write [roll, name, marks] records with pickle.dump().
- update_marks(roll, marks): load every record into a list until EOFError.
- Change the marks in the matching record.
- Rewrite all records to the file in "wb" mode.
- display(): load and print every record.
Program
# Binary file: update the marks of a student import pickle def create_file(): n = int(input("How many students? ")) with open("result.dat", "wb") 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 display(): with open("result.dat", "rb") as f: try: while True: print(pickle.load(f)) except EOFError: pass def update_marks(roll, new_marks): records = [] with open("result.dat", "rb") as f: try: while True: records.append(pickle.load(f)) except EOFError: pass found = False for rec in records: if rec[0] == roll: rec[2] = new_marks found = True with open("result.dat", "wb") as f: for rec in records: pickle.dump(rec, f) return found create_file()print("Before update:")display()r = int(input("Roll number to update: "))m = int(input("New marks : "))if update_marks(r, m): print("After update:") display()else: print("Roll number not found")
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python binary_file_update.py
How many students? 3
Roll number: 1
Name : Asha
Marks : 78
Roll number: 2
Name : Rohan
Marks : 64
Roll number: 3
Name : Kabir
Marks : 88
Before update:
[1, 'Asha', 78]
[2, 'Rohan', 64]
[3, 'Kabir', 88]
Roll number to update: 2
New marks : 71
After update:
[1, 'Asha', 78]
[2, 'Rohan', 71]
[3, 'Kabir', 88]
✓ Printed by running this program, not typed by hand.
Result
Rohan's record (roll number 2) changed from 64 to 71 marks; the other two records were written back unchanged.
Viva voce: what the examiner may ask
01Why can't a single record be changed directly in the file?
Pickled records can have different sizes, so the simplest safe way is to read all records, change one, and write them all back.
02What does the function return and why?
True or False, so the caller knows whether the roll number was found.
03What is the difference between "wb" and "ab"?
"wb" erases the file and writes from the start; "ab" adds to the end of the existing file.
Variations for the lab test
- Increase the marks of every student by 5.
- Delete the record of a given roll number.
- Update the name instead of the marks.
! Common mistake Opening the file in "ab" mode to save the changes adds a second copy of every record instead of replacing them.