Computer Science - Class 12
Solutions to CBSE Sample Paper - Computer Science Class 12

Aman is a Python programmer. He has written a code and created a binary file record.dat with employeeid, ename and salary. The file contains 10 records. He now has to update a record based on the employee id entered by the user and update the salary. The updated record is then to be written in the file temp.dat. The records which are not to be updated also have to be written to the file temp.dat. If theemployee id is not found, an appropriate message should to be displayed.

As a Python expert, help him to complete the following code based on the requirement given above:

import _______ #Statement 1

def update_data():

rec={}

fin=open("record.dat","rb")

fout=open("_____________") #Statement 2

found=False

eid=int(input("Enter employee id to update their

salary :: "))

while True:

try:

rec=______________ #Statement 3

if rec["Employee id"]==eid:

found=True

rec["Salary"]=int(input("Enter new salary

:: "))

pickle.____________ #Statement 4

else:

pickle.dump(rec,fout)

except:

break

if found==True:

print("The salary of employee id ",eid," has

been updated.")

else:

print("No employee with such id is not found")

fin.close()

fout.close()

 

Question 35(i)

Which module should be imported in the program? (Statement 1)

 

Answer:

The pickle module should be imported in the program since we are dealing with binary files.

 

Question 35(ii)

Write the correct statement required to open a temporary file named temp.dat. (Statement 2)

 

Answer:

fout=open( 'temp.dat', 'wb' ) #statement 2

 

Explanation:

Syntax to open a binary file for writing:

file_object=open(‘filename.dat’,’wb’)

  • ‘wb’ mode opens the file in binary format for writing.

 

Question 35(iii)

Which statement should Aman fill in Statement 3 to read the data from the binary file, record.dat and in Statement 4 to write the updated data in the file, temp.dat?

 

Answer:

pickle.load(fin) #statement 3

pickle.dump(rec,fout) #statement 4

 

Explanation:

Statement 3: The load method of pickle module is used to read data from a binary file. It takes the file object as an argument.

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science and Computer Science at Teachoo