[Type B] File Handling – Chapter 5 Sumita Arora
Table of Contents
16. Identify the error in the following code.
Python
import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb':
pickle.dump(data)
Answer: The error in this code is a missing closing parenthesis in the open
function call. The open
function call should be open('data.dat', 'wb')
instead of open('data.dat', 'wb':
.
Here’s the corrected code:
Python
import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb') as f:
pickle.dump(data, f)
This code opens the file data.dat
in binary write mode and passes the file object f
to the pickle.dump
function to serialize and write the data
object to the file.
Other Improvements: to the code
- Incorrect File Extension: The code uses the extension
.dat
for the file, while thepickle
module usually uses.pkl
to store serialized data. While it’s technically possible to use other extensions, it’s recommended to stick with.pkl
for clarity and consistency, especially when using thepickle
module.
Good work posting these questions in detail!