CBSE Class 12 Computer Science
Question 115 of 145
File Handling — Question 11
Back to all questionsDunzo
import pickle— Imports thepicklemodule, which is used for serializing and deserializing Python objects.ID = {1: "Ziva", 2: "53050", 3: "IT", 4: "38", 5: "Dunzo"}— Defines a dictionary namedIDwith keys and values.fin = open("Emp.pkl", "wb")— Opens a file namedEmp.pklin binary write mode ("wb").pickle.dump(ID, fin)— Serializes theIDdictionary and writes it to the file handlefinusing thepickle.dump()function.fin.close()— Closes the filefinafter writing the pickled data.fout = open("Emp.pkl", 'rb')— Opens the fileEmp.pklagain, this time in binary read mode ("rb"), to read the pickled data.ID = pickle.load(fout)— Deserializes the data from the filefoutusing thepickle.load()function and assigns it to the variableID. This effectively restores the original dictionary from the pickled data.print(ID[5])— Prints the value associated with key 5 in the restoredIDdictionary, which is "Dunzo".