Skip to content
Question

Q.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)
(ii) Write the correct statement required to open the binary file "items.dat". (Statement 2)
(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".
(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".
CBSECBSE Class XII Board 2023Subjective· 4mImportance★★★★★
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Part (a): import pickle; open items.dat in "rb"; open new_items.dat in "wb"; item_detail=pickle.load(f1). Part (b): condition if key != 101: and write with pickle.dump({key:item_detail[key]}, f2).

Binary files store whole Python objects using the pickle module (load to read, dump to write). The stored object is a dictionary {item_id:[item_name,amount]}.

Part (a)

  1. module — Statement 6 calls pickle.dump, so the module is pickle.
  2. open items.dat — it already exists and we read it, so read-binary mode "rb": f1=open("items.dat","rb").
  3. Statements 3 and 4 — new_items.dat is created for output, so write-binary mode "wb"; the whole dictionary is read at once with pickle.load.
import pickle                      # Statement 1
def Copy_new():
    f1 = open("items.dat", "rb")       # Statement 2
    f2 = open("new_items.dat", "wb")   # Statement 3
    item_id = int(input("Enter the item id"))
    item_detail = pickle.load(f1)      # Statement 4
    ... …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.