Q. 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 a parameter and count and return number of books by the given Author are stored in the binary file "Book.dat".


You can understand by Watching video :-



Answer :-

import pickle

def CreateFile():
    f = open("Book.dat", "wb")
    while True :
        num = int(input("Enter Book Number :- "))
        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("For exit (Enter exit):- ")
        print()
        if choice == "exit" or choice == "Exit":
            print("Thank you")
            print()
            break
    f.close()

def CoutRec(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)

CreateFile()
print("For Searching -")
aut = input("Enter Author :- ")
CoutRec(aut)

Output :-

Enter Book Number :- 1
Enter Book Name :- Python
Enter Author :- Path Walla
Enter Price of Book :- 150.0
For exit (Enter exit):- no

Enter Book Number :- 51
Enter Book Name :- Css
Enter Author :- Portal Express
Enter Price of Book :- 89.5
For exit (Enter exit):- no

Enter Book Number :- 100
Enter Book Name :- Html
Enter Author :- CP
Enter Price of Book :- 158.6
For exit (Enter exit):- no

Enter Book Number :- 111
Enter Book Name :- C++
Enter Author :- Path Walla
Enter Price of Book :- 145.6
For exit (Enter exit):- exit

Thank you

For Searching -
Enter Author :- Path Walla
Number of Book with Author name Path Walla = 2

>>>


7 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post