Computer Science
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' = ...............}
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
Related Questions
Write a program that will create an object called filout for writing, associate it with the filename STRS.txt. The code should keep on writing strings to it as long as the user wants.
Consider the following definition of a dictionary Member, write a method in Python to write the content in a pickled file member.dat.
Member = {'MemberNo.': ..............., 'Name': ...............}
Considering the following definition of dictionary COMPANY, write a method in Python to search and display the content in a pickled file COMPANY.DAT, where CompID key of the dictionary is matching with the value '1005'.
Company = {'CompID' = ........., 'CName' = ........., 'Turnover' = .........}
Write a function to search and display details of all trains, whose destination is "Delhi" from a binary file "TRAIN.DAT". Assuming the binary file is containing the objects of the following dictionary type:
Train = {'Tno': ..............., 'From': ...............,'To': ...............}