29

我正在尝试学习如何pickle在 python 中保存一个对象。但是,当我使用下面的示例代码时,我收到以下错误:io.UnsupportedOperation: read它可以追溯到favorite_color = pickle.load(f_myfile). 我找不到这个特定错误的一个很好的解释。我做错了什么,我该如何纠正?

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()
4

1 回答 1

69

改变:

# Read from file 
f_myfile = open('myfile.pickle', 'wb')

至:

f_myfile = open('myfile.pickle', 'rb')

你可以看到你腌制的 dict obj 。

于 2013-09-23T16:11:24.623 回答