Computer Science

Write a program to enter the following records in a binary file :

Item No — integer
Item_Name — string
Qty — integer
Price — float

Number of records to be entered should be accepted from the user. Read the file to display the records in the following format:

Item No :
Item Name :
Quantity :
Price per item :
Amount : ( to be calculated as Price * Qty)

Python File Handling

1 Like

Answer

import pickle

with open("item.dat", 'wb') as itemfile:
    n = int(input("How many records to be entered? "))
    for i in range(n):
        ino = int(input("Enter item no: "))
        iname = input("Enter item name: ")
        qty = int(input("Enter quantity: "))
        price = float(input("Enter price: "))
        item = {"Item no": ino, "Item Name": iname, "Qty": qty, "Price": price}
        pickle.dump(item, itemfile)
    print("Successfully written item data")


with open("item.dat", "rb") as file:
    try:
        while True:
            item = pickle.load(file)
            print("\nItem No:", item["Item no"])
            print("Item Name:", item["Item Name"])
            print("Quantity:", item["Qty"])
            print("Price per item:", item["Price"])
            print("Amount:", item["Qty"] * item["Price"])
    except EOFError:
        pass  
Output
How many records to be entered? 5
Enter item no: 11
Enter item name: Mobile
Enter quantity: 4
Enter price: 20000
Enter item no: 12
Enter item name: Laptop
Enter quantity: 2
Enter price: 35000
Enter item no: 13
Enter item name: Computer
Enter quantity: 1
Enter price: 50000
Enter item no: 14
Enter item name: Television
Enter quantity: 4
Enter price: 25000 

Item No: 11
Item Name: Mobile
Quantity: 4
Price per item: 20000.0
Amount: 80000.0

Item No: 12
Item Name: Laptop
Quantity: 2
Price per item: 35000.0
Amount: 70000.0

Item No: 13
Item Name: Computer
Quantity: 1
Price per item: 50000.0
Amount: 50000.0

Item No: 14
Item Name: Television
Quantity: 4
Price per item: 25000.0
Amount: 100000.0

Answered By

1 Like


Related Questions