Test Index
File Handling in Python
© examsnet.com
Question : 30 of 37
Marks:
+1,
-0
(a) Write one difference between CSV and text files.Write a program in Python that defines and calls the following user defined functions :(i)
COURIER_ADD(): It takes the values from the user and adds the details to a csv file 'courier.csv'. Each record consists of a list with field elements as cid, s_name, Source, destination to store Courier ID, Sender name, Source and destination address respectively.(ii) COURIER_SEARCH() : Takes the destination as the input and displays all the courier records going to that destination.OR(b) Why it is 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 as book_ID, B_name and pub to store book ID, book name and publisher respectively.(ii) Search_Book() : Takes publisher name as input and counts and displays number of books published by them.[CBSE 2023 Set 4]
Solution:
(a) Difference: A CSV file stores tabular data as values separated by commas and can be opened in a spreadsheet; Python handles it with the
csv module. A text file stores plain lines of characters, is opened in a text editor and needs no special module.import csvdef COURIER_ADD(): f = open("courier.csv", "a", newline="") w = csv.writer(f) cid = int(input("Enter Courier ID: ")) s_name = input("Enter Sender name: ") Source = input("Enter Source address: ") destination = input("Enter Destination address: ") w.writerow([cid, s_name, Source, destination]) f.close()def COURIER_SEARCH(): f = open("courier.csv", "r") r = csv.reader(f) dest = input("Enter destination to search: ") for rec in r: if rec[3] == dest: print(rec) f.close()COURIER_ADD()COURIER_SEARCH()Explanation: Mode "a" adds new records without deleting the old ones; writerow() writes one list as one row. csv.reader() gives each row as a list, so rec[3] is the destination.OR (b) Why close a file: Data written to a file is first kept in a buffer in memory. close() flushes (writes) this unsaved data to the file and frees the resources tied to the file; without it data may be lost.import csvdef Add_Book(): f = open("Book.csv", "a", newline="") w = csv.writer(f) book_ID = int(input("Enter Book ID: ")) B_name = input("Enter Book name: ") pub = input("Enter Publisher: ") w.writerow([book_ID, B_name, pub]) f.close()def Search_Book(): f = open("Book.csv", "r") r = csv.reader(f) name = input("Enter publisher name: ") count = 0 for rec in r: if rec[2] == name: count += 1 print("Number of books:", count) f.close()Add_Book()Search_Book()Explanation: rec[2] is the publisher of each record; the counter is increased for every match and printed at the end.© examsnet.com
Go to Question: