Python Program to Update Marks in a Binary File
Intermediate · File handling · CBSE class 12 practical list
This program creates a binary file of student records (roll number, name and marks) with the pickle module, then changes the marks of the student with a given roll number. The safe way to do it is to read every record, change the one that matches and write them all back. It is a standard CBSE class 12 practical program.
Program
Before: [[101, 'Aarav', 78], [102, 'Diya', 85], [103, 'Kabir', 64]] Changing marks of Kabir from 64 to 72 Roll number 110 not found, nothing updated After: [[101, 'Aarav', 78], [102, 'Diya', 85], [103, 'Kabir', 72]]
How it works
- The program writes three records to
students.datwithpickle.dump, one record per call. read_all()loads the records one by one untilEOFErrorsays the file has ended, and returns them as a list.update_marks()looks for the roll number in that list and changes the marks of the matching record withrecord[2] = new_marks.- Opening the file again with "wb" empties it, and the loop dumps every record back, now with the new marks.
returnends the function after a successful update, so the not found message is printed only when no record matched, as for roll number 110.
Another way to write it
Updating the record in place with seek()
Updated: [102, 'Diya', 91]
Many textbooks use this "rb+" version. It overwrites the record where it sits, which is safe only when the new record takes exactly as many bytes as the old one: marks from 0 to 255 always do, but a longer name would damage the records after it. Rewriting the whole file, as in the main program, is safe for any change.
Try it yourself
Change the program to add 5 bonus marks to every student instead of updating just one.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Search a Roll Number in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Find Students Who Scored Above 75 Using a Dictionary
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Count the Words "Me" and "My" in a Text File
- Display Lines Starting with T in a Text File
- Count Words in a Text File
All Python programs · CBSE class 12 practical file · Python exercises