Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Pickling in Python: io.UnsupportedOperation: read

Tags:

python

pickle

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() 
like image 885
Michael Avatar asked Sep 23 '13 16:09

Michael


People also ask

How do you read a file with pickles?

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.

What is pickling in Python example?

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.

What Cannot be pickled in Python?

With pickle protocol v1, you cannot pickle open file objects, network connections, or database connections.

What is pickling method in Python?

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.


Video Answer


1 Answers

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.

like image 168
Jay Choo Avatar answered Sep 20 '22 08:09

Jay Choo