[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:
- Serializing Data: The code first creates a dictionary named
ID
and then serializes it using thepickle
module. It writes the serialized data to a file named “Emp.pkl”. - Closing and Reopening File: The file is closed and then reopened in read-binary mode (
"rb"
) for reading the serialized data. - Loading Data: The
pickle.load()
function loads the serialized dictionary back into theID
variable. - Accessing Value: The code prints the value associated with the key
5
in theID
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.
Good work posting these questions in detail!