Question 34(or)
2 April 2024 · Computer Science (083)
(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]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.
Answer
(i) The advantage of using the with clause is that any file opened using it is closed automatically once control leaves the with block — even if an exception is raised.
Syntax:
with open(file_name, access_mode) as file_object:
# operationsExample:
with open("myfile.txt", "r+") as file_object:
content = file_object.read()(ii)
import pickle
def disp_Detail():
try:
with open("EMP.DAT", "rb") as F:
try:
while True:
Data = pickle.load(F)
if Data[2] < 25000:
print(Data)
except EOFError:
pass
except:
print("File Not Found!!!")Explanation
(i) The 'with' clause auto-closes files and handles cleanup. (ii) Loops through pickled records, filters by Salary index [2] < 25000.