Question 33(2)
30 March 2023 · Computer Science (083)
Why is it important to close a file before exiting ? Write a program in Python that defines and calls the following user defined functions :
(i) Add_Book() — Takes the details of the books and adds them to a csv file 'Book.csv'. Each record consists of a list with field elements book_ID, B_name, pub to store book ID, book name and publisher respectively.
(ii) Search_Book() — Takes the publisher name as input and counts and displays the number of books published by them.
Answer
Why close a file ? It is important to close a file before exiting so that any unwritten or buffered data is flushed to disk and the system resources held by the file (file descriptor, memory buffers) are released back to the OS.
import csv
def Add_Book():
f1 = open("Book.csv", "a", newline="")
writ = csv.writer(f1)
book_ID = int(input("Enter the Book id: "))
B_name = input("Enter the Book Name: ")
pub = input("Enter the Publisher Name: ")
detail = [book_ID, B_name, pub]
writ.writerow(detail)
f1.close()
def Search_Book():
f1 = open("Book.csv", "r")
detail = csv.reader(f1)
name = input("Enter the Publisher Name to be searched: ")
pub_count = 0
for i in detail:
if i[2] == name:
pub_count += 1
print("NUMBER OF BOOKS: ", pub_count)
f1.close()
Add_Book()
Search_Book()Explanation
Add_Book opens 'Book.csv' in append mode and writes a single row. Search_Book reads each row and increments a counter whenever index 2 (publisher) matches the input.