CBSE Class 12 Computer Science Question 36 of 43

Practice Paper — Question 7

Back to all questions
7
Question

Question 30

A binary file "salary.Dat" has structure [employee id, employee name, salary]. Write a function countrec() in Python that would read contents of the file "salary.Dat" and display the details of those employees whose salary is above 20000.

Answer

Let the "salary.dat" file contain following sample data:

[[101, 'Aditi', 25000], [102, 'Jatin', 19000], [103, 'Minaz', 28000]]
import pickle
def countrec(file_name):    
    f1 = open(file_name, 'rb')
    while True:
        try:
            employees = pickle.load(f1)
            for employee in employees:
                if (employee[2] > 20000):
                    print("Employee ID:", employee[0], "Name:", employee[1], "Salary:", employee[2])
        except EOFError:
                    break
    f1.close()
countrec("salary.dat")
Output
Employee ID: 101 Name: Aditi Salary: 25000
Employee ID: 103 Name: Minaz Salary: 28000