Test Index
CBSE Class 12 Computer Science 2026 Paper Set 4
© examsnet.com
Question : 36 of 37
Marks:
+1,
-0
NextStep is an organization which has a pool of resource persons to conduct training workshops on various topics related to ICT. The data of all its Resource Persons is stored in a binary file RESOURCES.DAT using the following record structure (each record is a tuple) :(R_ID, R_Name, R_Expertise, Charges)where :R_ID – Resource Person’s ID (An integer)R_Name – Resource Person’s Name (A string)R_Expertise – Area of expertise of the Resource PersonCharges – Charges (in rupees) per hour to conduct a workshopFor example, a record in the file is :(12, 'P. Velusami','Machine Learning',5000)In this context, write the following user defined functions in Python :(i) Append() – To input the data of a Resource Person and write it in the file RESOURCES.DAT.(ii) Update() – To increase the Charges of each resource person by 500.
Solution:
Concept:A binary file is written and read with the pickle module: pickle.dump(obj, file) writes one object, pickle.load(file) reads the next object and raises EOFError when the file ends. Each record here is a separate tuple dumped one after another.(i) Append()Open the file in "ab" (append binary) mode so old records are kept, input the four fields, form the tuple and dump it.
import pickledef Append(): F = open("RESOURCES.DAT", "ab") # append in binary mode R_ID = int(input("Enter Resource Person ID: ")) R_Name = input("Enter Name: ") R_Expertise = input("Enter Area of Expertise: ") Charges = int(input("Enter Charges per hour: ")) Rec = (R_ID, R_Name, R_Expertise, Charges) pickle.dump(Rec, F) # write the tuple F.close()(ii) Update()A tuple cannot be changed in place, so read every record into a list, then rewrite the file with a new tuple whose Charges value is 500 more.import pickledef Update(): Records = [] F = open("RESOURCES.DAT", "rb") # 1. read all records try: while True: Rec = pickle.load(F) Records.append(Rec) except EOFError: pass F.close() F = open("RESOURCES.DAT", "wb") # 2. write them back for Rec in Records: NewRec = (Rec[0], Rec[1], Rec[2], Rec[3] + 500) pickle.dump(NewRec, F) F.close()Explanation:• The while True loop with try ... except EOFError reads records until the end of the file.• Rec[3] is Charges (index 3 of the tuple), so the example record (12, 'P. Velusami', 'Machine Learning', 5000) becomes (12, 'P. Velusami', 'Machine Learning', 5500).• Opening in "wb" empties the file, and all updated records are written back in the same order.Key point: Use "ab" for adding a record ("wb" would erase the existing records). Updating in place with "rb+", tell() and seek() is also accepted, but reading all records and rewriting the file is safer because the pickled size of a record can change.© examsnet.com
Go to Question: