Python Program to Search a Roll Number in a Binary File
Intermediate · File handling · CBSE class 12 practical list
A binary file stores Python objects such as lists and dictionaries exactly as they are, using Python's pickle module, instead of as plain text. This program creates a binary file of student records (roll number and name), then searches it for a roll number and prints the name, or a message when the roll number is not in the file. It is a standard CBSE class 12 practical program.
Program
Roll number 103 found, name: Kabir Roll number 110 not found in the file
How it works
- Files opened with "wb" (write binary) and "rb" (read binary) hold raw bytes, which is what
pickleneeds. - Each
pickle.dump(record, f)call writes one record, so the file ends up holding four records one after another. pickle.load(f)reads one record per call, and thewhile Trueloop keeps reading until the file runs out and Python raisesEOFError, which theexceptblock catches.- When the roll number matches, the name is printed and
breakstops the search early. - For roll number 110 nothing matches, so
foundis stillFalseafter the loop and the not found message is printed.
Another way to write it
Storing all the records in one list
Roll number 102 found, name: Diya
Dumping the whole list once means a single pickle.load reads everything back, with no EOFError loop. The else of a for loop runs only when the loop ends without break, that is, when nothing matched.
Try it yourself
Add marks as a third value in every record and print the marks along with the name when the roll number is found.
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
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Search for an Element in a List
- 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