Q. 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 :-

It will give an error because we can not write in a binary file by using write(), we have to use pickle.dump() .

So, the correct program is 

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)

Output : -

['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None]]
>>> 

2 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post