Computer Science · Ch 2 — File Handling in Python
The load() method
The load() method
The load() method is the counterpart of dump() — it brings data back from a binary file into a Python object. This process is called unpickling. While dump() writes (pickles) an object to a file, load() reads (unpickles) that stored object from the file so you can use it again in your program.
To use load(), the file must first be opened in binary read mode, which is "rb". If you try to open it in text mode or in write mode, the method will fail because the file contains pickled (binary) data, not plain text.
The syntax is straightforward:
store_object = load(file_object)
Here, file_object is the file handle of the binary file that has been opened in "rb" mode. The load() function reads the pickled data from that file and returns the original Python object, which is then assigned to a variable — in the syntax above, that variable is called store_object. You can name this variable anything meaningful; it simply holds the unpickled data.
Program 2-7: Unpickling data in Python
import pickle
print("The data that were stored in file are: ")
fileobject = open("mybinary.dat", "rb")
objectvar = pickle.load(fileobject)
fileobject.close()
print(objectvar)
Output of Program 2-7:
>>>
RESTART: Path_to_file\Program2-7.py
The data that were stored in file are:
[1, 'Geetika', 'F', 26]
>>>
Notice the steps: the pickle module is imported first. Then the file mybinary.dat is opened in "rb" mode. The load() method reads the single pickled object from the file and stores it in objectvar. After that, the file is closed with fileobject.close(). Finally, print(objectvar) displays the unpickled list — exactly the same list that was originally dumped into the file. …