Test Index

File Handling in Python Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 21 of 37
Marks: +1, -0
(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]
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.
[CBSE 2024 Set 4]
Solution:  
(A)(i)
'w' (write) mode'a' (append) mode
Opens the file for writing; creates the file if it does not exist.Opens the file for appending; creates the file if it does not exist.
If the file exists, its old contents are erased (truncated).If the file exists, its old contents are kept.
The file pointer is at the beginning of the file.The file pointer is at the end of the file, so new data is added after the old data.
(A)(ii)
import pickle
def Copy_new():
F1 = open("items.dat", "rb")
F2 = open("new_items.dat", "wb")
try:
while True:
rec = pickle.load(F1) # {item_id: [item_name, amount]}
new_rec = {}
for k, v in rec.items():
if v[1] > 1000: # amount
new_rec[k] = v
if new_rec: # copy only if it qualifies
pickle.dump(new_rec, F2)
except EOFError: # end of items.dat
pass
F1.close()
F2.close()
Explanation: Records are read one by one with pickle.load() until EOFError is raised at the end of the file. For each dictionary, the amount is v[1]; the items with amount above 1000 are written to new_items.dat with pickle.dump().
OR (B)(i)
Advantage: a file opened with the with clause is closed automatically when the control leaves the with block, even if an error occurs, so we do not have to call close().
Syntax:
with open(file_name, access_mode) as file_object:
statements
Example:
with open("notes.txt", "r") as F:
data = F.read()
OR (B)(ii)
import pickle
def disp_Detail():
with open("EMP.DAT", "rb") as F:
try:
while True:
rec = pickle.load(F) # [Emp_Id, Name, Salary]
if rec[2] < 25000:
print(rec)
except EOFError: # end of file
pass
Explanation: Each record is a list; rec[2] is the salary. Every record with salary below 25000 is displayed.
© examsnet.com
Advertisements
Go to Question: