20 questions from CBSE board, sample and compartment papers (2024–2027), 1 to 5 marks, each with a model answer. Questions on binary file modes, pickle dump() and load(), adding, searching and updating records in a binary file, and CSV files with csv.writer, writerow(), writerows() and csv.reader. Programming answers open in the Python Lab.
File Handling in Python (Binary & CSV file)· 1 Mark· Q17· 2024 Board Paper
Assertion (A): CSV file is a human readable text file where each line has a number of fields, separated by comma or some other delimiter.
Reason (R): writerow() method is used to write a single row in a CSV file.
Mark the correct choice as:
(A)Both (A) and (R) are true and (R) is the correct explanation for (A).
(B)Both (A) and (R) are true and (R) is not the correct explanation for (A).
(C)(A) is true but (R) is false.
(D)(A) is false but (R) is true.
Model answer
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
Explanation: Both statements are true facts, but writerow() is merely a module method and does not explain why CSV files are formatted as delimited text.
File Handling in Python (Binary & CSV file)· 4 Marks· Q32· 2024 Board Paper Python
Sangeeta is a Python programmer working in a computer hardware company. She has to maintain the records of the peripheral devices. She created a csv file named Peripheral.csv, to store the details. The structure of Peripheral.csv is: [P_id, P_name, Price]
where P_id is Peripheral device ID (integer), P_name is Peripheral device name (String), Price is Peripheral device price (integer).
Sangeeta wants to write the following user defined functions:
Add_Device() : to accept a record from the user and add it to a csv file, Peripheral.csv.
Count_Device() : To count and display number of peripheral devices whose price is less than 1000.
Model answer
import csv
def Add_Device():
f = open("Peripheral.csv", "a", newline="")
w = csv.writer(f)
p_id = int(input("Enter Peripheral ID: "))
p_name = input("Enter Peripheral Name: ")
price = int(input("Enter Price: "))
w.writerow([p_id, p_name, price])
f.close()
def Count_Device():
f = open("Peripheral.csv", "r")
r = csv.reader(f)
count = 0
for row in r:
if int(row[2]) < 1000:
count += 1
print("Number of peripheral devices with price < 1000:", count)
f.close()
import csv
import io
buf = io.StringIO()
w = csv.writer(buf)
w.writerow([101, "Mouse", 450])
w.writerow([102, "Keyboard", 850])
w.writerow([103, "Monitor", 7500])
def Count_Device_demo(stream):
stream.seek(0)
r = csv.reader(stream)
count = sum(1 for row in r if int(row[2]) < 1000)
print("Devices under 1000:", count)
Count_Device_demo(buf)
File Handling in Python (Binary & CSV file)· 5 Marks· Q34· 2024 Board Paper Python
(A) (i) Differentiate between 'w' and 'a' file modes in Python.
(ii) 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.
OR
(B) (i) What is the advantage of using with clause while opening a data file in Python? Also give syntax of with clause.
(ii) A binary file, EMP.DAT has the following structure:
[Emp_Id, Name, 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.
Model answer
(A) (i) 'w' (Write mode) creates a new file or overwrites/truncates existing file content from the beginning. 'a' (Append mode) creates a new file or appends new data to the end of the existing file without erasing prior data.
(ii)
import pickle
def Copy_new():
fin = open("items.dat", "rb")
fout = open("new_items.dat", "wb")
try:
while True:
rec = pickle.load(fin)
for item_id, details in rec.items():
if details[1] > 1000:
pickle.dump(rec, fout)
except EOFError:
pass
fin.close()
fout.close()
OR
(B) (i) Advantage of with clause: Ensures automatic file closure and cleanup upon exiting the block, even if runtime exceptions occur.
Syntax: with open("filename", "mode") as file_handle:
(ii)
import pickle
def disp_Detail():
f = open("EMP.DAT", "rb")
try:
while True:
emp = pickle.load(f)
if emp[2] < 25000:
print("Emp_Id:", emp[0], "Name:", emp[1], "Salary:", emp[2])
except EOFError:
pass
f.close()
import pickle
import io
buf = io.BytesIO()
pickle.dump({101: ["Laptop", 55000]}, buf)
pickle.dump({102: ["Mouse", 450]}, buf)
pickle.dump({103: ["Keyboard", 1500]}, buf)
def demo_copy(stream):
stream.seek(0)
copied = []
try:
while True:
rec = pickle.load(stream)
for k, v in rec.items():
if v[1] > 1000:
copied.append(rec)
except EOFError:
pass
print("Copied items (>1000):", copied)
demo_copy(buf)
File Handling in Python (Binary & CSV file)· 1 Mark· Q20· 2025 Board Paper
Assertion (A): For a binary file opened using 'rb' mode, the pickle.dump() method will display an error.
Reason (R): The pickle.dump() method is used to read from a binary file.
(A)Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation for Assertion (A).
(B)Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation for Assertion (A).
(C)Assertion (A) is true but, Reason (R) is false.
(D)Assertion (A) is false but, Reason (R) is true.
Model answer
Assertion (A) is true but, Reason (R) is false.
Explanation: 'rb' is read-only, so dump() (write) fails. dump() writes data, load() reads data.
File Handling in Python (Binary & CSV file)· 4 Marks· Q33· 2025 Board Paper Python
A csv file "P_record.csv" contains the records of patients in a hospital. Each record of the file contains the following data:
- Name of a patient
- Disease
- Number of days patient is admitted
- Amount
For example, a sample record of the file may be:
["Gunjan","Jaundice",4,15000]
Write the following Python functions to perform the specified operations on this file:
(i) Write a function read_data() which reads all the data from the file and displays the details of all the 'Cancer' patients.
(ii) Write a function count_rec() which counts and returns the number of records in the file.
import csv
# Mocking CSV content (NOT USED AS PER QUESTION)
# csv_content = [['Gunjan', 'Jaundice', 4, 15000], ['Amit', 'Cancer', 10, 50000]]
def read_data():
with open('P_record.csv', 'r', newline='') as file:
reader = csv.reader(file)
for row in reader:
if row[1].lower() == 'cancer':
print(row)
def count_rec():
count = 0
with open('P_record.csv', 'r', newline='') as file:
reader = csv.reader(file)
for row in reader:
count += 1
return count
# Function Calls
read_data()
print('Total Records:', count_rec())
File Handling in Python (Binary & CSV file)· 5 Marks· Q36· 2025 Board Paper Python
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:
(i) Create() - to input data for passengers and write it in the binary file PASSENGERS.DAT.
(ii) 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.
(iii) UpdateFare() - to increase the fare of all passengers by 5% and rewrite the updated records into the file PASSENGERS.DAT.
import pickle
# Mocking input (NOT USED AS PER QUESTION)
# data_store.append(['101', 'Rahul', 'Delhi', 'Mumbai', 5000])
def Create():
with open('PASSENGERS.DAT', 'ab') as f:
ans = 'y'
while ans.lower() == 'y':
pnr = input('Enter Passenger Number: ')
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, f)
ans = input('Add more records (y/n)? ')
def SearchDestn(D):
found = False
with open('PASSENGERS.DAT', 'rb') as f:
try:
while True:
record = pickle.load(f)
if record[3].lower() == D.lower():
print(record)
found = True
except EOFError:
if not found:
print('No matching record found')
def UpdateFare():
records = []
with open('PASSENGERS.DAT', 'rb') as f:
try:
while True:
record = pickle.load(f)
record[4] = record[4] * 1.05
records.append(record)
except EOFError:
pass
with open('PASSENGERS.DAT', 'wb') as f:
for rec in records:
pickle.dump(rec, f)
# Function Calls (for testing)
# Create()
# SearchDestn('Mumbai')
# UpdateFare()
File Handling in Python (Binary & CSV file)· 1 Mark· Q10· 2026 Board Paper
Consider the statement given below:
f1 = open("pqr.dat", "_______")
Which of the following is the correct file mode to open the file in read only mode?
(A)a
(B)rb
(C)r+
(D)rb+
Model answer
rb
Explanation: 'rb' opens a binary file strictly for reading.
File Handling in Python (Binary & CSV file)· 4 Marks· Q33· 2026 Board Paper Python
A csv file "States.csv" contains [State, Capital, Population, Language]. Write a Python program which reads data from this file and appends records where population is more than 10000000 into another csv file 'More.csv'. Note: Skip the Header row.
import csv
import os
# Creating mock data
with open('States.csv', 'w', newline='') as f:
w = csv.writer(f)
w.writerow(['State', 'Capital', 'Population', 'Language']) # Header
w.writerow(['Andhra Pradesh', 'Amaravati', 52221000, 'Telugu']) # > 10M
w.writerow(['Sikkim', 'Gangtok', 610577, 'Nepali']) # < 10M
# Solution Implementation
with open('States.csv', 'r') as F1:
with open('More.csv', 'a', newline='') as F2:
R = csv.reader(F1)
W = csv.writer(F2)
RECS = list(R)
for rec in RECS[1:]: # Skip header
if int(rec[2]) > 10000000:
W.writerow(rec)
# Verification
with open('More.csv', 'r') as check:
print(check.read())
File Handling in Python (Binary & CSV file)· 5 Marks· Q36· 2026 Board Paper Python
Binary file 'RESOURCES.DAT' stores (R_ID, R_Name, R_Expertise, Charges). Write: (i) Append() to input data and write to file. (ii) Update() to increase Charges of each resource person by 500.
import pickle
import os
def Append():
# Mocked input values: 12, 'P. Velusami', 'Machine Learning', 5000
Rec = (12, 'P. Velusami', 'Machine Learning', 5000)
with open("RESOURCES.DAT", "ab") as F:
pickle.dump(Rec, F)
def Update():
records = []
if not os.path.exists("RESOURCES.DAT"): return
# Read
with open("RESOURCES.DAT", "rb") as F:
try:
while True:
records.append(list(pickle.load(F)))
except EOFError:
pass
# Update
with open("RESOURCES.DAT", "wb") as F:
for rec in records:
rec[3] += 500
pickle.dump(tuple(rec), F)
print("Updated Record:", tuple(rec))
# Run Functions
Append()
Update()
File Handling in Python (Binary & CSV file)· 4 Marks· Q33· 2025 Compartment Paper Python
Write Python code for a CSV file 'CLUB.CSV' [Mno, Name, Mobile, Fee]:
NewMembers(): accept records from user and add to file.
PriorityMember(): find and display members paying Fee > 35000.
import csv
# Mocking execution by writing to an in-memory test file
file_name = "test_club.csv"
def NewMembers(records):
with open(file_name, "a", newline='') as F:
Writer = csv.writer(F)
for rec in records:
Writer.writerow(rec)
print("Records Added!")
def PriorityMember():
with open(file_name, "r") as F:
Recs = csv.reader(F)
for R in Recs:
if len(R) == 4:
fee = float(R[3])
if fee > 35000:
print("Priority Member:", R)
# Simulated Input
mock_records = [
[1, 'Alice', '999', 40000],
[2, 'Bob', '888', 25000]
]
NewMembers(mock_records)
PriorityMember()
File Handling in Python (Binary & CSV file)· 5 Marks· Q36· 2025 Compartment Paper Python
Records of doctors are stored in a binary file 'DOCTORS.DAT' [D_ID, D_Name, D_Dept, Experience].
(I) Write one difference between binary and CSV files.
(II) Write a Python function to read and display all records.
(III) Write a Python function to add a doctor.
import pickle
import os
# (I) Binary files store data in a non-human-readable format, making it harder to alter from a text editor, whereas CSV files are plain text.
def AddDoctor(doc_list):
with open("test_doctors.dat", "ab") as F:
for doc in doc_list:
pickle.dump(doc, F)
def displayDoctors():
if not os.path.exists("test_doctors.dat"):
return
with open("test_doctors.dat", "rb") as F:
try:
while True:
data = pickle.load(F)
print(data)
except EOFError:
pass
# Test logic
AddDoctor([[1256, 'R. Gupta', 'Cardiology', 15]])
print("--- Displaying Records ---")
displayDoctors()
File Handling in Python (Binary & CSV file)· 4 Marks· Q32· 2024 Sample Paper Python
Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has created a csv file named Result.csv, to store the results of students in different sports events. The structure of Result.csv is :
[St_Id, St_Name, Game_Name, Result]
Where
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'
For efficiently maintaining data of the event, Vedansh wants to write the following user defined functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column headings should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event.
As a Python expert, help him complete the task.
Model answer
import csv
def Accept():
sid=int(input("Enter Student ID "))
sname=input("Enter Student Name ")
game=input("Enter name of game ")
res=input("Enter Result ")
headings=["Student ID", "Student Name", "Game Name", "Result"]
data=[sid,sname,game,res]
f=open('Result.csv','a',newline='')
csvwriter=csv.writer(f)
csvwriter.writerow(headings)
csvwriter.writerow(data)
f.close()
def wonCount():
f=open('Result.csv','r')
csvreader=csv.reader(f, delimiter=',')
head=list(csvreader)
print(head[0])
for x in head:
if x[3]=="WON" or x[3]=="Won":
print(x)
f.close()
import csv
import io
def demo():
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(["Student ID", "Student Name", "Game Name", "Result"])
writer.writerow([1, "Aman", "Chess", "Won"])
writer.writerow([2, "Ravi", "Cricket", "Lost"])
buf.seek(0)
reader = csv.reader(buf)
rows = list(reader)
for r in rows[1:]:
if r[3] in ["WON", "Won"]:
print("Winner:", r)
demo()
File Handling in Python (Binary & CSV file)· 5 Marks· Q34· 2024 Sample Paper Python
(i) Differentiate between r+ and w+ file modes in Python.
(ii) Consider a file, SPORT.DAT, containing records of the following structure:
[SportName, TeamName, No_Players]
Write a function, copyData(), that reads contents from the file SPORT.DAT and copies the records with Sport name as “Basket Ball” to the file named BASKET.DAT. The function should return the total number of records copied to the file BASKET.DAT.
OR
(i) How are text files different from binary files?
(ii) A Binary file, CINEMA.DAT has the following structure:
{MNO:[MNAME, MTYPE]}
Where
MNO – Movie Number
MNAME – Movie Name
MTYPE is Movie Type
Write a user defined function, findType(mtype), that accepts mtype as parameter and displays all the records from the binary file CINEMA.DAT, that have the value of Movie Type as mtype.
Model answer
(i)
r+ mode:
• Primary function is reading
• File pointer is at beginning of file
• if the file does not exist, it results in an error
w+ mode:
• primary function is writing
• if the file does not exist, it creates a new file.
• If the file exists, previous data is overwritten
• File pointer is at the beginning of file
(ii)
def copyData():
fObj = open("SPORT.DAT", "rb")
fObj1 = open("BASKET.DAT", "wb")
cnt=0
try:
while True:
data = pickle.load(fObj)
print(data)
if data[0] == "Basket Ball":
pickle.dump(data, fObj1)
cnt+=1
except:
fObj.close()
fObj1.close()
return cnt
OR
(i) Text files:
• Extension is .txt
• Data is stored in ASCII format that is human readable
• Has EOL character that terminates each line of data stored in the text files
Binary Files:
• Extension is .dat
• Data is stored in binary form (0s and 1s), that is not human readable.
(ii)
def Searchtype(mtype):
fObj = open("CINEMA.DAT", "rb")
try:
while True:
data = pickle.load(fObj)
if data[2] == mtype:
print("Movie number:", data[0])
print("Movie Name:", data[1])
print("Movie Type:", data[2])
except EOFError:
fObj.close()
File Handling in Python (Binary & CSV file)· 4 Marks· Q33· 2025 Sample Paper
A csv file "Happiness.csv" contains the data of a survey. Each record of the file contains the following data:
● Name of a country
● Population of the country
● Sample Size (Number of persons who participated in the survey in that country)
● Happy (Number of persons who accepted that they were Happy) For example, a sample record of the file may be:
['Signiland', 5673000, 5000, 3426] Write the following Python functions to perform the specified operations on this file:
(I) Read all the data from the file in the form of a list and display all those records for which the population is more than 5000000.
(II) Count the number of records in the file.
import csv
def show_large():
f = open("Happiness.csv", "r", newline="")
for row in csv.reader(f):
if int(row[1]) > 5000000:
print(row)
f.close()
def count_records():
f = open("Happiness.csv", "r", newline="")
count = 0
for row in csv.reader(f):
count += 1
f.close()
return count
File Handling in Python (Binary & CSV file)· 5 Marks· Q36· 2025 Sample Paper
Surya is a manager working in a recruitment agency. He needs to manage the records of various candidates. For this, he wants the following information of each candidate to be stored:
- Candidate_ID - integer
- Candidate_Name - string
- Designation - string
- Experience - float
You, as a programmer of the company, have been assigned to do this job for Surya.
(I) Write a function to input the data of a candidate and append it in a binary file.
(II) Write a function to update the data of candidates whose experience is more than 10 years and change their designation to "Senior Manager".
(III) Write a function to read the data from the binary file and display the data of all those candidates who are not "Senior Manager".
import pickle
def add_candidate():
f = open("candidates.dat", "ab")
cid = int(input("Candidate ID: "))
name = input("Name: ")
desig = input("Designation: ")
exp = float(input("Experience: "))
pickle.dump([cid, name, desig, exp], f)
f.close()
def update_designation():
records = []
f = open("candidates.dat", "rb")
try:
while True:
rec = pickle.load(f)
if rec[3] > 10:
rec[2] = "Senior Manager"
records.append(rec)
except EOFError:
f.close()
f = open("candidates.dat", "wb")
for rec in records:
pickle.dump(rec, f)
f.close()
def show_others():
f = open("candidates.dat", "rb")
try:
while True:
rec = pickle.load(f)
if rec[2] != "Senior Manager":
print(rec)
except EOFError:
f.close()
File Handling in Python (Binary & CSV file)· 4 Marks· Q33· 2026 Sample Paper Python
Raj is the manager of a medical store. To keep track of sales records, he has created a CSV file named Sales.csv, which stores the details of each sale. The columns of the CSV file are: Product_ID, Product_Name, Quantity_Sold and Price_Per_Unit. Help him to efficiently maintain the data by creating the following user-defined functions:
I. Accept() – to accept a sales record from the user and add it to the file Sales.csv.
II. CalculateTotalSales() – to calculate and return the total sales based on the Quantity_Sold and Price_Per_Unit.
import csv
# Mocking CSV file write/read in memory
def Accept():
# Simulating input for the runner
rec = [101, "Paracetamol", 10, 50]
print("Added record:", rec)
return rec
def TotalSales(records):
total = 0
for row in records:
total += int(row[2]) * float(row[3])
print("Total Sales is:", total)
# Test
data = [Accept(), [102, "Syrup", 5, 100]]
TotalSales(data)
File Handling in Python (Binary & CSV file)· 5 Marks· Q36· 2026 Sample Paper Python
Mr. Ravi, a manager at a tech company, needs to maintain records of employees. Each record should include: Employee_ID, Employee_Name, Department and Salary. Write the Python functions to:
I. Input employee data and append it to a binary file.
II. Update the salary of employees in the "IT" department to 200000.
import pickle
# Mocking file operations
employees = [
[1, "Ravi", "HR", 50000],
[2, "Amit", "IT", 150000]
]
def update_salary():
for emp in employees:
if emp[2] == "IT":
emp[3] = 200000
print(f"Updated Salary for {emp[1]}")
print(employees)
update_salary()
File Handling in Python (Binary & CSV file)· 1 Mark· Q20· 2027 Sample Paper
Assertion (A): Opening a file in mode rb allows you to read a binary file without modifying it.
Reason (R): In rb mode, if the file does not exist, Python creates a new empty file.
(A)Both A and R are True and R is the correct explanation for A.
(B)Both A and R are True and R is not the correct explanation for A.
(C)A is True but R is False.
(D)A is False but R is True.
Model answer
c) A is true, but R is false
File Handling in Python (Binary & CSV file)· 4 Marks· Q33· 2027 Sample Paper
Kabir runs a vehicle rental agency and maintains a CSV file named Rentals.csv.
The file stores daily rental details with columns:
Vehicle_ID, Vehicle_Type, Hours_Rented, Rate_Per_Hour
Create the following user-defined functions:
I. AddRental() – to accept rental details from the user and append them to Rentals.csv.
II. CalculateTotalRent() – to calculate and return the total rent earned (Hours_Rented × Rate_Per_Hour).
Model answer
import csv
def AddRental():
Vehicle_ID = input("Enter Vehicle ID: ")
Vehicle_Type = input("Enter Vehicle Type: ")
Hours_Rented = input("Enter Hours Rented: ")
Rate_Per_Hour = input("Enter Rate Per Hour: ")
with open("Rentals.csv", "a") as f:
w = csv.writer(f)
w.writerow([Vehicle_ID, Vehicle_Type, Hours_Rented, Rate_Per_Hour])
print("Rental record added successfully.")
def CalculateTotalRent():
total = 0
f = open("Rentals.csv", "r")
r = csv.reader(f)
for row in r:
hours = int(row[2])
rate = int(row[3])
total += hours * rate
print("Total Rent Earned:", total)
f.close()
import csv
def AddRental():
Vehicle_ID = input("Enter Vehicle ID: ")
Vehicle_Type = input("Enter Vehicle Type: ")
Hours_Rented = input("Enter Hours Rented: ")
Rate_Per_Hour = input("Enter Rate Per Hour: ")
with open("Rentals.csv", "a") as f:
w = csv.writer(f)
w.writerow([Vehicle_ID, Vehicle_Type, Hours_Rented, Rate_Per_Hour])
print("Rental record added successfully.")
def CalculateTotalRent():
total = 0
f = open("Rentals.csv", "r")
r = csv.reader(f)
for row in r:
hours = int(row[2])
rate = int(row[3])
total += hours * rate
print("Total Rent Earned:", total)
f.close()
File Handling in Python (Binary & CSV file)· 5 Marks· Q36· 2027 Sample Paper
A college administrator, Atul, maintains student course enrollment records.
Each record includes Roll_No, Student_Name, Course, Fees.
Write Python functions to:
I. Input enrollment details and append them to a binary file.
II. Update the Fees of all students enrolled in the "Data Science" course to 75000.
Model answer
I.
def AddEnrollment():
Roll = int(input("Enter Roll No: "))
Name = input("Enter Student Name: ")
Course = input("Enter Course: ")
Fees = int(input("Enter Fees: "))
rec = [Roll, Name, Course, Fees] # LIST record
with open("Enrollments.dat", "ab") as f:
pickle.dump(rec, f)
print("Record added successfully.")
II.
import pickle
def UpdateFees():
updated = False
records = []
with open("Enrollments.dat", "rb") as file:
try:
while True:
rec = pickle.load(file)
if rec[2] == "Data Science": # Course at index 2
rec[3] = 75000 # Fees at index 3
updated = True
records.append(rec)
except EOFError:
pass
with open("Enrollments.dat", "wb") as file:
for rec in records:
pickle.dump(rec, file)
if updated:
print("Fees updated for Data Science students.")
else:
print("No student enrolled in Data Science found.")
import pickle
def AddEnrollment():
Roll = int(input("Enter Roll No: "))
Name = input("Enter Student Name: ")
Course = input("Enter Course: ")
Fees = int(input("Enter Fees: "))
rec = [Roll, Name, Course, Fees]
with open("Enrollments.dat", "ab") as f:
pickle.dump(rec, f)
print("Record added successfully.")
def UpdateFees():
updated = False
records = []
with open("Enrollments.dat", "rb") as file:
try:
while True:
rec = pickle.load(file)
if rec[2] == "Data Science":
rec[3] = 75000
updated = True
records.append(rec)
except EOFError:
pass
with open("Enrollments.dat", "wb") as file:
for rec in records:
pickle.dump(rec, file)
if updated:
print("Fees updated for Data Science students.")
else:
print("No student enrolled in Data Science found.")