Arrange the following program statements in correct sequence in order to read the contents from a binary file:
A. var = pickle.load(fileobj)
B. fileobj = open("mybinary.dat", "rb")
C. print(var)
D. import pickle
Arrange the following program statements in correct sequence in order to read the contents from a binary file:
A. var = pickle.load(fileobj)
B. fileobj = open("mybinary.dat", "rb")
C. print(var)
D. import pickle
Solution
D. import pickle comes first, since pickle.load() cannot be used until the module is imported.
B. fileobj = open("mybinary.dat", "rb") opens the file in binary read mode and creates the file object.
A. var = pickle.load(fileobj) reads the data from that open file object into var.
C. print(var) displays the data, so var must already hold a value.
Option 2: prints var before it has been loaded, which raises a NameError.
Option 4: calls pickle.load(fileobj) before fileobj exists.
Option 1: uses pickle before it is imported and fileobj before it is created.
Remember the order for reading a binary file: import, open, load, use. Writing follows the same pattern with "wb" and pickle.dump().
Related questions:
2026: 11 May Shift 2
2025: 22 May Shift 1