Test Index

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

© examsnet.com
Question : 37 of 37
Marks: +1, -0
Atharva is a programmer, who has recently been given a task to write a Python code to perform the following binary file operation with the help of a user defined function/module :
• Copy_new() : to create a binary file new_items.dat and write all the item details stored in the binary file, items.dat, except for the item whose item_id is 101. The data is stored in the following format :
{item_id:[item_name,amount]}
import ___________                     # Statement 1
def Copy_new():
f1=_____________ # Statement 2
f2=_____________ # Statement 3
item_id=int(input("Enter the item id"))
item_detail=___________ # Statement 4
for key in item_detail:
if _______________: # Statement 5
pickle.___________ # Statement 6
f1.close()
f2.close()
He has succeeded in writing partial code and has missed out certain statements. Therefore, as a Python expert, help him to complete the code based on the given requirements :
(i) Which module should be imported in the program ? (Statement 1) (1)
(ii) Write the correct statement required to open the binary file "items.dat". (Statement 2) (1)
(iii) Which statement should Atharva fill in Statement 3 to open the binary file "new_items.dat" and in Statement 4 to read all the details from the binary file "items.dat". (2)
OR (Option for part iii only)
(iii) What should Atharva write in Statement 5 to apply the given condition and in Statement 6 to write data in the binary file "new_items.dat". (2)
[CBSE 2023 Compartment]
Solution:  
(i) Statement 1: import pickle (the module for writing and reading Python objects in a binary file).
(ii) Statement 2: f1=open("items.dat","rb") (read binary mode).
(iii)
Statement 3: f2=open("new_items.dat","wb") (write binary mode, creates the new file)
Statement 4: item_detail=pickle.load(f1) (reads the dictionary stored in items.dat)
OR (iii)
Statement 5: if key != item_id: (item_id entered as 101; key != 101 also works)
Statement 6: pickle.dump({key: item_detail[key]}, f2)
Every item except the given item_id is written to new_items.dat by dump(), in the same {item_id:[item_name,amount]} format.
Complete code:
import pickle
def Copy_new():
f1 = open("items.dat", "rb")
f2 = open("new_items.dat", "wb")
item_id = int(input("Enter the item id"))
item_detail = pickle.load(f1)
for key in item_detail:
if key != item_id:
pickle.dump({key: item_detail[key]}, f2)
f1.close()
f2.close()
© examsnet.com
Advertisements
Go to Question: