[Type B] File Handling – Chapter 5 Sumita Arora

|
Table of Contents

12. What will be the output of the following code?

Python
import pickle
ID = {1:"Ziva",2:"53050",3:"IT",4:"38",5:"Dunzo"}
fin = open("Emp.pkl","wb")
pickle.dump(ID, fin)
fin.close()
fout = open("Emp.pkl", 'rb')
ID = pickle.load(fout)
print( ID [5] )

Answer: The output of the code will be:

Python
Dunzo

Explanation:

  1. Serializing Data: The code first creates a dictionary named ID and then serializes it using the pickle module. It writes the serialized data to a file named “Emp.pkl”.
  2. Closing and Reopening File: The file is closed and then reopened in read-binary mode ("rb") for reading the serialized data.
  3. Loading Data: The pickle.load() function loads the serialized dictionary back into the ID variable.
  4. Accessing Value: The code prints the value associated with the key 5 in the ID dictionary, which is "Dunzo".

Key Points:

  • The pickle module is used for serializing and deserializing Python objects, allowing data to be stored and retrieved from files.
  • The code demonstrates how to serialize a dictionary, store it in a file, and then load it back into a variable for further use.
  • Note: When working with files in a real-world scenario, it’s a good practice to use a context manager (with open()) to ensure that the file is properly closed after use.
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *

One Comment