Introduction:
Data retrieval is a vital aspect of programming, and Python’s pickle module simplifies the process through unpickling. This tutorial dives into the art of unpickling, explaining how to extract serialized data from binary files. By demonstrating the process with practical examples, you’ll gain insights into how to effectively retrieve stored data using Python.
Code:
import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
Logic:
- Display “The data that were stored in file are: ” to set the context for the output.
- Open the binary file “mybinary.dat” in binary read mode (“rb”) and assign the file object to fileobject.
- Use the pickle.load() function to unpickle (deserialize) data from the binary file and assign it to the variable objectvar.
- Close the binary file using the close() method.
- Print the content of objectvar.
Output:
>>The data that were stored in file are:
>>[1, ‘Geetika’, ‘F’, 26]