Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
Quick Tips
- • Import random module for number generation
- • Use randint(1, 6) for dice simulation
- • Handle user input validation properly
Binary File Search & Display Records
AIM
To write a Python program to search and display all records from a binary file that match specific criteria.
ALGORITHM
- Start
- Import pickle module
- Define search criteria
- Open binary file in read mode
- Read all records using pickle.load()
- Filter records based on search criteria
- Display matching records in formatted manner
- Close the file
- Stop
PROGRAM
import pickle
def display_all_records():
try:
with open('employee.dat', 'rb') as file:
print("All Employee Records:")
print("=" * 50)
record_count = 0
try:
while True:
record = pickle.load(file)
record_count += 1
print(f"Record {record_count}:")
print(f"ID: {record['id']}")
print(f"Name: {record['name']}")
print(f"Department: {record['dept']}")
print(f"Salary: {record['salary']}")
print("-" * 30)
except EOFError:
print(f"Total records displayed: {record_count}")
except FileNotFoundError:
print("File not found!")
except Exception as e:
print(f"Error: {e}")
def search_by_department():
try:
with open('employee.dat', 'rb') as file:
dept_name = input("Enter department to search: ")
print(f"Employees in {dept_name} department:")
print("=" * 40)
found = False
try:
while True:
record = pickle.load(file)
if record['dept'].lower() == dept_name.lower():
print(f"Name: {record['name']}")
print(f"ID: {record['id']}")
print(f"Salary: {record['salary']}")
print("-" * 25)
found = True
except EOFError:
if not found:
print("No records found for this department!")
except FileNotFoundError:
print("File not found!")
except Exception as e:
print(f"Error: {e}")
# Main program
if __name__ == "__main__":
choice = input("1. Display all records\n2. Search by department\nEnter choice: ")
if choice == '1':
display_all_records()
elif choice == '2':
search_by_department()
else:
print("Invalid choice!")OUTPUT
1. Display all records
2. Search by department
Enter choice: 2
Enter department to search: IT
Employees in IT department:
========================================
Name: Alice Johnson
ID: 101
Salary: 75000
-------------------------
CONCLUSION
Thus, the program to search and display records from a binary file was successfully executed and verified.
VIVA QUESTIONS
What is EOFError in Python?
EOFError is raised when the input() function hits an end-of-file condition or when pickle.load() reaches the end of file.
How do you handle file exceptions in Python?
Use try-except blocks to catch FileNotFoundError, IOError, and other file-related exceptions.