Class - 12 CBSE Computer Science Important File Handling Questions 2025
Consider the following definition of dictionary Staff, write a method in python to search and display content in a pickled file staff.dat, where Staffcode key of the dictionary is matching with 'S0105'.
Staff = {'Staffcode': ..............., 'Name' = ...............}
Python File Handling
5 Likes
Answer
Let the file "staff.dat" include following data:
Staff1 = {'Staffcode': 'S0102', 'Name': 'Sanya'}
Staff2 = {'Staffcode': 'S0104', 'Name': 'Anand'}
Staff3 = {'Staffcode': 'S0105', 'Name': 'Aditya'}
import pickle
def search_and_display_staff(staff_code):
found = False
try:
file = open("staff.dat", "rb")
while True:
staff_data = pickle.load(file)
if staff_data['Staffcode'] == staff_code:
print("Staffcode:", staff_data['Staffcode'])
print("Name:", staff_data['Name'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
search_and_display_staff('S0105')
Output
Staffcode: S0105
Name: Aditya
Answered By
2 Likes