CBSE · 083Class XII · 2023Section E5 marks

Question 33(1)

30 March 2023 · Computer Science (083)

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 cid, s_name, Source, destination to store Courier ID, Sender name, Source and Destination address respectively.

(ii) COURIER_SEARCH() — Takes the destination as input and displays all the courier records going to that destination.

Answer

Difference between CSV and Text files : - CSV files can be viewed in spreadsheets and require the csv module to be imported; text files can be viewed in a text editor and need no special module. - CSV files store records as comma-separated values; text files store free-form text.

python
import csv

def COURIER_ADD():
    f1 = open("courier.csv", "a", newline="")
    writ = csv.writer(f1)
    cid = int(input("Enter the Courier id: "))
    s_name = input("Enter the Sender Name: ")
    Source = input("Enter the Source Address: ")
    destination = input("Enter Destination Name: ")
    detail = [cid, s_name, Source, destination]
    writ.writerow(detail)
    f1.close()

def COURIER_SEARCH():
    f1 = open("courier.csv", "r")
    detail = csv.reader(f1)
    name = input("Enter the Destination Name to be searched: ")
    for i in detail:
        if i[3] == name:
            print("Details of courier are: ", i)
    f1.close()

COURIER_ADD()
COURIER_SEARCH()

Explanation

COURIER_ADD opens the CSV in append mode and writes a list of fields with csv.writer. COURIER_SEARCH iterates rows using csv.reader and matches index 3 (destination) against the user's input.