When you use python 3.5 pickle library to save a python object to a file, you may encouter TypeError: file must have a ‘write’ attribute error. In this tutorial, we will introduce how to fix this error to help you save python object to a file.
Here is an example:
import pickle list = [1, 2, 3] pickle.dump(list, 'binary_list.bin')
Then you will get this error: TypeError: file must have a ‘write’ attribute
The function pickle.dump() is defined as:
pickle.dump(obj, file, protocol=None, *, fix_imports=True)
Here file is not the name of a file, it is a file object.
To fix this error, we should open a file then use pickle.dump().
The solution is here.
with open("binary_list.bin","wb") as f: pickle.dump(list, f)
Then you will find binary_list.bin file is created and python list is saved into this file.