1.

A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. i. Write a user defined function CreateFile() to input data for a record and add to Book.dat . ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter and count and return number of books by the given Author are stored in the binary file “Book.dat”

Answer»

Using of any correct code giving the same result is also accepted.

import pickle 

def createFile(): 

fobj=open("Book.dat","ab") 

BookNo=int(input("Book Number : ")) 

Book_name=input("Name :") 

Author = input(“Author: “) 

Price = int(input("Price : "))

rec=[BookNo,Book_Name,Author,Price] 

pickle.dump(rec,fobj) 

fobj.close() 

def CountRec(Author): 

fobj=open("Book.dat","rb") 

num = 0 

try: 

while True: 

rec=pickle.load(fobj) 

if Author==rec[2]: 

num = num + 1 

except: 

fobj.close() 

return num



Discussion

No Comment Found

Related InterviewSolutions