Programming Examples

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


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

Item No integer

Item_Name string

Quantity 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 * Quantity)

Solution

import pickle

filename = "items.dat"

n = int(input("Enter the number of records: "))

file = open(filename, "wb")

for i in range(n):
    print("\nEnter Details of Item", i + 1)

    item_no = int(input("Enter Item No: "))
    item_name = input("Enter Item Name: ")
    quantity = int(input("Enter Quantity: "))
    price = float(input("Enter Price per Item: "))

    record = [item_no, item_name, quantity, price]
    pickle.dump(record, file)

file.close()


# Reading Records from Binary File

print("\n----- ITEM DETAILS -----")

file = open(filename, "rb")

try:
    while True:
        record = pickle.load(file)

        amount = record[2] * record[3]

        print("\nItem No       :", record[0])
        print("Item Name     :", record[1])
        print("Quantity      :", record[2])
        print("Price per Item:", record[3])
        print("Amount        :", amount)

except EOFError:
    file.close()
Output

Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Best Website and Software Company in Allahabad