CBSE Class 12 Computer Science Question 120 of 145

File Handling — Question 16

Back to all questions
16
Question

Question 15

Identify the error in the following code.

import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb' :
  pickle.dump(data)
Answer
import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb' : #error 1
  pickle.dump(data) #error 2
  1. There is a syntax error in the open() function call. The closing parenthesis is missing in the open() function call. Also, file handle is not mentioned.
  2. The pickle.dump() function requires two arguments - the object to be pickled and the file object to which the pickled data will be written. However, in the provided code, the pickle.dump() function is missing the file object argument.

The corrected code is :

import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb') as f:
  pickle.dump(data, f)