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

A Binary file, CINEMA.DAT has the following structure:

{MNO:[MNAME, MTYPE]}

Where

MNO – Movie Number

MNAME – Movie Name

MTYPE is Movie Type

Write a user defined function, findType(mtype), that accepts mtype as parameter and displays all the records from the binary file CINEMA.DAT, that have the value of Movie Type as mtype.

Answer

Answer by student

Function in Python to display records from a Binary file that match a criteria - Teachoo.png

Detailed answer by teachoo

The question asks us to write a user defined function, findType(mtype) , that accepts mtype as parameter and displays all the records from the binary file CINEMA.DAT , that have the value of Movie Type as mtype .

To write this function, we can follow these steps:

  • Define a function named findType with one parameter named mtype using the def keyword.
  • Open the binary file CINEMA.DAT in read mode using the built-in open function. This will create a file object that we can use to read data from the file. We assign this object to a variable named cinema_file . The mode “rb” means read binary mode, which allows us to read binary data from the file.
  • Loop through the records in the file using a for loop . Each iteration will assign one record from the file to a variable named record .
  • Unpack the record into a dictionary using the pickle module’s load function. The load function takes a file object as an argument and returns an object that was previously serialized using the pickle module’s dump function. In this case, we pass record as an argument and expect to get a dictionary with keys “MNO”, “MNAME”, and “MTYPE”. We assign this dictionary to a variable named movie .
  • Check if the movie type matches the parameter using an if statement . In this case, the condition is movie[“MTYPE”] == mtype. This will use the == operator to compare two strings and see if they are exactly equal (case-sensitive). If they are equal, the condition will be True and the following block of code will be executed.
  • Display the movie details using the print function. In this case, we want to print the movie number, name, and type, so we pass movie[“MNO”], movie[“MNAME”], and movie[“MTYPE”] as arguments.
  • Close the file using the close method. 

Here is the code with comments that explains each step:

Function in Python (with comments) to display records from a Binary file that match a criteria - Teachoo.png

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, Social Science, Physics, Chemistry, Computer Science at Teachoo.