Question 4: Binary File Operations
Write a menu-driven program to add and display records in a binary file which contains at least three product records with the following fields:
pname(str)price(float)qty(int)
Solution
# Q4. Write a program to create a binary file 'products.dat' using pickle module.
# The program should have a menu with options to:
# 1. Add a new product (with product name, price, and quantity)
# 2. Display all products stored in the file
# 3. Exit the program
import pickle
# Function to add a new record
def add_record():
# 'ab' opens for appending; it creates the file if it doesn't exist
with open("products.dat", "ab") as f:
pname = input("Enter Product Name: ")
price = float(input("Enter Price: "))
qty = int(input("Enter Quantity: "))
record = [pname, price, qty]
pickle.dump(record, f)
print("Product added successfully!")
# Function to display all records
def display_records():
print("\n--- Product List ---")
print('Product Name',",",'Price,',",",'Quantity')
print("-" * 40)
try:
with open("products.dat", "rb") as f:
while True:
try:
rec = pickle.load(f)
print(rec[0],",",rec[1],",",rec[2])
except EOFError:
break
except FileNotFoundError:
print("Error: The file does not exist yet. Add a record first!")
# --- Main Menu ---
while True:
print("\n1. Add Product")
print("2. Display All Products")
print("3. Exit")
choice = input("Enter choice (1-3): ")
if choice == "1":
add_record()
elif choice == "2":
display_records()
elif choice == "3":
print("Exiting...")
break
else:
print("Invalid choice!")
📌 Simple Solution (Click to expand)
import pickle
def add_record():
pname = input("Product Name: ")
price = float(input("Price: "))
qty = int(input("Quantity: "))
rec = [pname, price, qty]
with open("products.dat", "ab+") as fh:
pickle.dump(rec, fh)
def display():
print("Start >----------")
with open("products.dat", "rb+") as fh:
try:
while True:
data = pickle.load(fh)
print(data)
except Exception:
print("End >----------")
def menu():
while True:
print("1.add_record | 2.Display | 3.Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
add_record()
elif ch == 2:
display()
elif ch == 3:
break
else:
print("Somthing went wromg")
menu()