I am trying to learn how to pickle
and save an object in python. However, when I use the sample code below I get the following error: io.UnsupportedOperation: read
which traces back to favorite_color = pickle.load(f_myfile)
. I cannot find a good explanation of this particular error. What am I doing wrong and how do I correct it?
import pickle # or import cPickle as pickle # Create dictionary, list, etc. favorite_color = { "lion": "yellow", "kitty": "red" } # Write to file f_myfile = open('myfile.pickle', 'wb') pickle.dump(favorite_color, f_myfile) f_myfile.close() # Read from file f_myfile = open('myfile.pickle', 'wb') favorite_color = pickle.load(f_myfile) # variables come out in the order you put them in f_myfile.close()
To store a dictionary into a pickle file, first import the pickle to utilize it. After that, define your custom dictionary. The next step is to open a file and use a pickle. dump() to put or write the dictionary into the open file and close it.
Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script. # Python3 program to illustrate store. # efficiently using pickle module.
With pickle protocol v1, you cannot pickle open file objects, network connections, or database connections.
Pickle in Python is primarily used in serializing and deserializing a Python object structure. In other words, it's the process of converting a Python object into a byte stream to store it in a file/database, maintain program state across sessions, or transport data over the network.
Change:
# Read from file f_myfile = open('myfile.pickle', 'wb')
to:
f_myfile = open('myfile.pickle', 'rb')
and you can see the dict obj you've pickled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With