Q30. A binary file BOOK.DAT has structure (book no., book name ,author name and price ).
(i). Write a user defined function Create_File( ) to input data for a record and add to BOOK.DAT.
(ii). Write a user defined function Count_Rec( ) which accept the author name as parameter,
count and return number of a records given by the author in binary file BOOK.DAT.
Answers
Answer:
(i)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()
(ii)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
Explanation:
(i) Take input according to the given structure using the while loop, until the user enters "exit" or "Exit"
def CreateFile():
f = open("Book.dat", "wb")
while True :
num = int(input("Enter Book No. :- "))
name = input ("Enter Book Name :- ")
aut = input("Enter Author :- ")
pri = float(input("Enter Price of Book :- "))
lst= [ num, name, aut, pri]
pickle.dump( lst, f)
choice = input("To exit (Type exit):- ")
print()
if choice == "exit" or choice == "Exit":
print("Thank you")
print()
break
f.close()
(ii) Take the author name in as the arguments, and using file handling open the Book.dat file to check for the given author.
def CoutRec(aut):
print("For Searching -", aut)
f = open("Book.dat", "rb")
count = 0
try :
while True:
data = pickle.load(f)
if data[2] == aut :
count += 1
except EOFError:
f.close()
print("Number of Book with Author name", aut , "=", count)
[Note: pickle is a python library. The first line will be "import pickle"]
#SPJ3