KnowledgeBoat Logo

Computer Science

Give any one point of difference between a binary file and a CSV file.

Write a Program in Python that defines and calls the following user defined functions :

(a) add(). To accept and add data of an employee to a CSV file 'furdata.csv'. Each record consists of a list with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price respectively.

(b) search(). To display the records of the furniture whose price is more than 10000.

Python File Handling

1 Like

Answer

The difference between a binary file and CSV file is that binary files are used for storing complex data in a non-human-readable format and they store data in a sequence of bytes, while CSV files are plain text files used for storing structured tabular data in a human-readable text format.

Let the file "furdata.csv" include following data:

[1, table, 20000]
[2, chair, 12000]
[3, board, 10000]
import csv

def add():
    
    with open('furdata.csv', mode='a', newline='') as file:
        writer = csv.writer(file)
        fid = input("Enter furniture id: ")
        fname = input("Enter furniture name: ")
        fprice = float(input("Enter furniture price: "))
        writer.writerow([fid, fname, fprice])
        print("Record added successfully to 'furdata.csv'")
    
def search():
    found = False
    with open('furdata.csv', mode='r') as file:
        reader = csv.reader(file)
        print("Records of furniture with price more than 10000:")
        for row in reader:
            if len(row) == 3 and float(row[2]) > 10000:
                print("Furniture ID:", row[0])
                print("Furniture Name:", row[1])
                print("Furniture Price:", row[2])
                print()
                found = True
    
    if found == False:
        print("No records of furniture with price more than 10000 found")

add()
search()
Output
Enter furniture id: 9
Enter furniture name: desk
Enter furniture price: 3000
Record added successfully to 'furdata.csv'
Records of furniture with price more than 10000:
Furniture ID: 1
Furniture Name:  table
Furniture Price:  20000

Furniture ID: 2
Furniture Name:  chair
Furniture Price:  12000

Answered By

1 Like


Related Questions