Computer Science
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' = .........}
Answer
Let the file "COMPANY.DAT" include following data:
Company1 = {'CompID': '1001', 'CName': 'ABC', 'Turnover': 500000}
Company2 = {'CompID': '1003', 'CName': 'DEF', 'Turnover': 600000}
Company3 = {'CompID': '1005', 'CName': 'LMN', 'Turnover': 900000}
import pickle
def company(comp_id):
found = False
try:
file = open("COMPANY.DAT", "rb")
while True:
company_data = pickle.load(file)
if company_data['CompID'] == comp_id:
print("Company ID:", company_data['CompID'])
print("Company Name:", company_data['CName'])
print("Turnover:", company_data['Turnover'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
company('1005')
Output
Company ID: 1005
Company Name: LMN
Turnover: 900000
Related Questions
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': ...............}
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' = ...............}
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': ...............}
A binary file "Book.dat" has structure [BookNo, Book_Name, Author, Price].
(i) Write a user defined function CreateFile() to input data for a record and add to Book.dat.
(ii) Write a function CountRec(Author) in Python which accepts the Author name as parameter and count and return number of books by the given Author are stored in the binary file "Book.dat"