Write
& Read a List to a Binary File
import pickle
my_list = [10, 20, 30, 40, 50]
file = open("data.dat", "wb") # open file in write-binary mode
pickle.dump(my_list, file) # write the list to the file
file.close() # don't forget to close the
file
print("List successfully written to binary
file.")
read-binary mode
file = open("data.dat", "rb") # open file in read-binary mode
loaded_list = pickle.load(file) # read the list from the file
file.close()
print("List read from binary file:",
loaded_list)
Notes:
- wb
= write binary
- rb
= read binary
- pickle.dump(obj,
file) → writes object to file
pickle.load(file) → reads object from file
Write a Dictionary to a Binary File
import pickle
# Dictionary to write
my_dict = {
"name": "Pooja",
"age": 25,
"city": "Delhi"
}
# Open file in write-binary mode
file = open("data.dat", "wb")
pickle.dump(my_dict, file) # Serialize and write dictionary
file.close()
print("Dictionary successfully written to binary
file.")
file = open("data.dat", "rb")
loaded_dict = pickle.load(file) # Deserialize
file.close()
print("Dictionary
read from file:", loaded_dict)
EG: DUMP & LOAD USING BINARY FILE
import pickle
file = open("stud.dat", "wb")
while True:
rno =
int(input("\nEnter roll no - "))
name =
input("Enter name - ")
perc =
float(input("Enter percentage - "))
stream =
input("Enter stream - ")
pickle.dump(dets, file)
ans =
input("Want to enter another (y/n) - ")
if ans in
"nN":
break
file.close()
print("Student records saved successfully.")
file = open("stud.dat", "rb")
print("Student Records:\n")
while True:
try:
record =
pickle.load(file) # Load one record at a
time
print("Roll No:", record[0])
print("Name:", record[1])
print("Percentage:", record[2])
print("Stream:", record[3])
print("-" * 30)
except
EOFError:
break # End of file reached
file.close()
28th July 2025
Eg: Updated Code to Add Multiple Records
Without Overwriting:
import pickle
file = open("stud.dat", "ab") # Append binary mode
while True:
rno =
int(input("\nEnter roll no - "))
name =
input("Enter name - ")
perc =
float(input("Enter percentage - "))
stream =
input("Enter stream - ")
dets = [rno, name, perc, stream]
pickle.dump(dets, file)
ans =
input("Want to enter another (y/n) - ")
if ans in
"nN":
break
file.close()
print("Student records added successfully.")
READ FILE :
try:
file =
open("stud.dat", "rb")
# Open in read-binary mode
print("Student Records:\n")
while True:
try:
record = pickle.load(file) # Load
one record at a time
print("Roll No:", record[0])
print("Name:", record[1])
print("Percentage:", record[2])
print("Stream:", record[3])
print("-" * 30)
except
EOFError:
break # End of file reached
file.close()
except FileNotFoundError:
print("File not found. Please make sure 'stud.dat' exists.")
Q1. a)WAP that reads a binary file “emp” and display all records of employee one by one.
b) Display all records who are getting
salaries between 2500 and 300
Sol:
import pickle
my_list = [100, 202, 300, 400, 500]
# Write the list to a binary file
with open("data.dat", "wb") as
file:
pickle.dump(my_list, file)
print("List successfully written to binary
file.")
f1=open("data.dat", "rb")
e=pickle.load(f1)
for x in e:
print(x)
f1.close()
PART B
f1=open("data.dat", "rb")
e=pickle.load(f1)
for x in e:
if x
>= 200 and x <= 400:
print(x)
Q2.
1. A file, PASSENGERS.DAT, stores the records of passengers using the following structure:
[PNR, PName, BRDSTN, DESTN, FARE]
Where:
·
PNR
– Passenger Number (string type)
·
PName
– Passenger Name (string type)
·
BRDSTN
– Boarding Station Name (string type)
·
DESTN
– Destination Station Name (string type)
·
FARE
– Fare amount for the journey (float type)
Write user-defined functions in
Python for the following tasks:
a)
Create() – to input data for passengers and
write it in the binary file PASSENGERS.DAT.
b)
SearchDestn(D) – to read contents from the file
PASSENGERS.DAT and display the details of those passengers whose DESTN matches
with the value of D.
c)
UpdateFare() – to increase the fare of all
passengers by 5% and rewrite the updated records into the file PASSENGERS.DAT.
2. Consider a binary file, items.dat, containing records stored in the given format:
{item_id: [item_name, amount]}
Write a function, Copy_new(), that
copies all records whose amount is greater than 1000 from items.dat to
new_items.dat.
3. A binary file, EMP.DAT, has the
following structure:
[Emp_Id, Name, Salary]
Where:
- Emp_Id
: Employee ID
- Name
: Employee Name
- Salary
: Employee Salary
Write a user-defined function
disp_Detail() that would read the contents of the file EMP.DAT and display the
details of those employees whose salary is below 25000.
4. A binary file named “TEST.dat” has some records of the structure:
[TestId, Subject, MaxMarks,
ScoredMarks].
Write
a function in Python named DisplayAvgMarks(Sub) that will accept a subject as
an argument and read the contents of TEST.dat. The function will calculate
& display the Average of the ScoredMarks of the passed Subject on screen.
SOLUTIONS
1. A file, PASSENGERS.DAT, stores the records of passengers using the following structure:
[PNR, PName, BRDSTN, DESTN, FARE]
Where:
- PNR
– Passenger Number (string type)
- PName
– Passenger Name (string type)
- BRDSTN
– Boarding Station Name (string type)
- DESTN
– Destination Station Name (string type)
- FARE
– Fare amount for the journey (float type)
Write
user-defined functions in Python for the following tasks:
a) Create() – to input data for passengers and
write it in the binary file PASSENGERS.DAT.
b)
SearchDestn(D) – to read contents from the file
PASSENGERS.DAT and display the details of those passengers whose DESTN matches
with the value of D.
c)
UpdateFare() – to increase the fare of all
passengers by 5% and rewrite the updated records into the file PASSENGERS.DAT.
Sol.
import pickle
# a) Function to create and write
passenger data
def Create():
with open("PASSENGERS.DAT", "wb") as file:
while True:
pnr = input("Enter PNR:
")
pname = input("Enter Passenger
Name: ")
brdstn = input("Enter Boarding
Station: ")
destn = input("Enter
Destination Station: ")
fare = float(input("Enter
Fare: "))
record = [pnr, pname, brdstn,
destn, fare]
pickle.dump(record, file)
choice = input("Add another
record? (y/n): ")
if choice.lower() != 'y':
break
# b) Function to search passengers
by destination
import pickle
def SearchDestn(D):
try:
with open("PASSENGERS.DAT",
"rb") as file:
count = 0 # Counter for matching records
while True:
try:
record = pickle.load(file)
if record[3].lower() ==
D.lower():
print("PNR:",
record[0])
print("Name:", record[1])
print("Boarding:", record[2])
print("Destination:", record[3])
print("Fare:", record[4])
print("-" *
30)
count += 1
except EOFError:
break
if count == 0:
print("No passengers found
with destination:", D)
except FileNotFoundError:
print("PASSENGERS.DAT file not
found.")
# c) Function to update fare by 5%
def UpdateFare():
try:
updated_records = []
with open("PASSENGERS.DAT",
"rb") as file:
while True:
try:
record = pickle.load(file)
record[4] *= 1.05 # Increase fare by 5%
updated_records.append(record)
except EOFError:
break
with open("PASSENGERS.DAT",
"wb") as file:
for rec in updated_records:
pickle.dump(rec, file)
print("Fare updated successfully
for all passengers.")
except FileNotFoundError:
print("File not found.")
2. Consider a binary file, items.dat, containing records stored in the given format:
{item_id: [item_name, amount]}
Write a function, Copy_new(), that
copies all records whose amount is greater than 1000 from items.dat to
new_items.dat.
Sol.
import pickle
def Copy_new():
try:
with open("items.dat",
"rb") as infile, open("new_items.dat", "wb") as
outfile:
while True:
try:
record =
pickle.load(infile)
# Check each item in the
dictionary
for item_id, value in
record.items():
item_name, amount =
value
if amount > 1000:
pickle.dump({item_id: value}, outfile)
except EOFError:
break
except FileNotFoundError:
print("File not found.")
3. A binary file, EMP.DAT, has the
following structure:
[Emp_Id, Name, Salary]
Where:
- Emp_Id
: Employee ID
- Name
: Employee Name
- Salary
: Employee Salary
Write a user-defined function
disp_Detail() that would read the contents of the file EMP.DAT and display the
details of those employees whose salary is below 25000.
Sol.
import pickle
def disp_Detail():
try:
with open("EMP.DAT",
"rb") as file:
print("Employees with salary
below 25000:")
while True:
try:
emp = pickle.load(file)
if emp[2] < 25000:
print(f"Emp_ID:
{emp[0]}, Name: {emp[1]}, Salary: {emp[2]}")
except EOFError:
break
except FileNotFoundError:
print("EMP.DAT file not
found.")
4.
4. A binary file named “TEST.dat” has some records of the structure:
[TestId, Subject, MaxMarks, ScoredMarks].
Write a function in Python named
DisplayAvgMarks(Sub) that will accept a subject as an argument and read the
contents of TEST.dat. The function will calculate & display the Average of
the ScoredMarks of the passed Subject on screen.
Sol.
import pickle
def DisplayAvgMarks(Sub):
try:
with open("TEST.dat",
"rb") as file:
total = 0
count = 0
while True:
try:
record = pickle.load(file)
if record[1].lower() ==
Sub.lower(): # Match subject
total += record[3] # ScoredMarks
count += 1
except EOFError:
break
if count > 0:
avg = total / count
print(f"Average Scored Marks
in {Sub} = {avg:.2f}")
else:
print(f"No records found for
subject: {Sub}")
except FileNotFoundError:
print("TEST.dat file not
found.")
Comments
Post a Comment