[Type B] File Handling – Chapter 5 Sumita Arora
Table of Contents
13. What will be the output of the following code?
import pickle
List1 = ['Roza', {'a': 23, 'b': True}, (1, 2, 3), [['dogs', 'cats'], None] ]
List2 = ['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None] ]
with open('data.pkl', 'wb') as f:
f.write(List1)
with open('data.pkl', 'wb') as f :
f.write(List2)
with open('data.pkl', 'rb') as f :
List1 = pickle.load(f)
print(List1)
Answer: The given code contains an error that prevents it from producing the correct output.
The code first attempts to write two lists, List1
and List2
, to the file “data.pkl” in binary mode. However, there is a critical error in this approach. The write()
method of a file object in Python is designed to work with bytes, not entire Python objects. As a result, an error is shown.
Traceback (most recent call last):
File "incorrect_pickle_usage.py", line 5, in <module>
f.write(List1)
TypeError: expected bytes, not list
Here’s a corrected version of the code that addresses this issue:
import pickle
List1 = ['Roza', {'a': 23, 'b': True}, (1, 2, 3), [['dogs', 'cats'], None] ]
List2 = ['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None] ]
with open('data.pkl', 'wb') as f:
pickle.dump(List1 , f )
with open('data.pkl', 'wb') as f :
pickle.dump(List2 , f )
with open('data.pkl', 'rb') as f :
list1 = pickle.load(f)
print(list1)
The output of this code:
['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None]]
Alternative Approach:
Where we store both the lists into the binary file rather than the last accessed one. More details on this below.
import pickle
List1 = ['Roza', {'a': 23, 'b': True}, (1, 2, 3), [['dogs', 'cats'], None]]
List2 = ['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None]]
# Pickle both lists into a single byte stream
pickled_data = pickle.dumps([List1, List2])
# Open the file in binary write mode and write the pickled data
with open('data.pkl', 'wb') as f:
f.write(pickled_data)
# Open the file in binary read mode and read the pickled data back into a list
with open('data.pkl', 'rb') as f:
unpickled_data = pickle.load(f)
print(unpickled_data)
This corrected code effectively serializes both List1
and List2
into a single byte stream using pickle.dumps()
. It then writes this byte stream to the file “data.pkl”. When the file is opened for reading later, the pickled data is loaded back into a Python list using pickle.loads()
.
The output of this corrected code will be:
[['Roza', {'a': 23, 'b': True}, (1, 2, 3), [['dogs', 'cats'], None]], ['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None]]]
This demonstrates that the code successfully stores and retrieves the two lists using the pickle module.
Good work posting these questions in detail!