Computer Science
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"
Python File Handling
22 Likes
Answer
Let the file "Book.dat" include following data:
Book1 = [1001, Midnight's Children, Salman Rushdie, 29.99]
Book2 = [1004, A Suitable Boy, Vikram Seth, 59.9]
Book3 = [1003, The White Tiger, Aravind Adiga, 49.5]
Book4 = [1002, The Satanic Verses, Salman Rushdie, 39.23]
import pickle
def CreateFile():
file = open("Book.dat", "ab")
BookNo = int(input("Enter Book Number: "))
Book_Name = input("Enter Book Name: ")
Author = input("Enter Author Name: ")
Price = float(input("Enter Price: "))
record = [BookNo, Book_Name, Author, Price]
pickle.dump(record, file)
file.close()
def CountRec(authorName):
count = 0
found = False
try:
file = open("Book.dat", "rb")
while True:
record = pickle.load(file)
if record[2] == authorName:
count += 1
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search successful")
file.close()
return count
CreateFile()
author = input("Enter Author name to count books: ")
print("Number of books by", author, ":", CountRec(author))
Output
Enter Book Number: 1008
Enter Book Name: Three Thousand Stiches
Enter Author Name: Sudha Murty
Enter Price: 200
Enter Author name to count books: Salman Rushdie
Search successful
Number of books by Salman Rushdie : 2
Answered By
9 Likes
Related Questions
Considering the following definition of dictionary COMPANY, write a method in Python to search and display the content in a pickled file COMPANY.DAT, where CompID key of the dictionary is matching with the value '1005'.
Company = {'CompID' = ........., 'CName' = ........., 'Turnover' = .........}
Write a function to search and display details of all trains, whose destination is "Delhi" from a binary file "TRAIN.DAT". Assuming the binary file is containing the objects of the following dictionary type:
Train = {'Tno': ..............., 'From': ...............,'To': ...............}
Write a function Show_words() in python to read the content of a text file 'NOTES.TXT' and display only such lines of the file which have exactly 5 words in them.
Example, if the file contains :
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.Then the function should display the output as :
This is a sample file.
The file contains many sentences.Write a Python program to read a given CSV file having tab delimiter.