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()
▶ RUN

Output/ Explanation:

Latest Current Affairs 2026 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online MBA 2 years Online MCA Online BCA Best Website and Software Company in Allahabad