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' = .........}

Python File Handling

3 Likes

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

Answered By

3 Likes


Related Questions