Reputation: 13914
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()
Upvotes: 40
Views: 70079
Reputation: 31
You can also use:
f = open("myfile.dat", "wb+")
This is especially helpful when you must write and read the file but only want to open it once. Example:
with open(file_path, "wb+") as file:
# Write content from response to the file
file.write(response.content)
# Move the file pointer back to the beginning of the file and read
file.seek(0)
data = file.read(-1)
# Calculate a hash or something
Upvotes: 3
Reputation: 1016
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.
Upvotes: 88