本文翻译自:How can I use pickle to save a dict?
I have looked through the information that the Python docs give, but I'm still a little confused. 我已经仔细阅读了Python文档提供的信息,但仍然有些困惑。 Could somebody post sample code that would write a new file then use pickle to dump a dictionary into it? 有人可以张贴示例代码来编写新文件,然后使用pickle将字典转储到其中吗?
#1楼
参考:https://stackoom.com/question/l4RB/如何使用泡菜保存字典
#2楼
Try this: 尝试这个:
import pickle
a = {'hello': 'world'}
with open('filename.pickle', 'wb') as handle:
pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open('filename.pickle', 'rb') as handle:
b = pickle.load(handle)
print a == b
#3楼
>>> import pickle
>>> with open("/tmp/picklefile", "wb") as f:
... pickle.dump({}, f)
...
normally it's preferable to use the cPickle implementation 通常,最好使用cPickle实现
>>> import cPickle as pickle
>>> help(pickle.dump)
Help on built-in function dump in module cPickle:
dump(...)
dump(obj, file, protocol=0) -- Write an object in pickle format to the given file.
See the Pickler docstring for the meaning of optional argument proto.
#4楼
import pickle
dictobj = {'Jack' : 123, 'John' : 456}
filename = "/foldername/filestore"
fileobj = open(filename, 'wb')
pickle.dump(dictobj, fileobj)
fileobj.close()
#5楼
# Save a dictionary into a pickle file.
import pickle
favorite_color = {"lion": "yellow", "kitty": "red"} # create a dictionary
pickle.dump(favorite_color, open("save.p", "wb")) # save it into a file named save.p
# -------------------------------------------------------------
# Load the dictionary back from the pickle file.
import pickle
favorite_color = pickle.load(open("save.p", "rb"))
# favorite_color is now {"lion": "yellow", "kitty": "red"}
#6楼
I've found pickling confusing (possibly because I'm thick). 我发现酸洗令人困惑(可能是因为我很胖)。 I found that this works, though: 我发现这可行,但是:
myDictionaryString=str(myDictionary)
Which you can then write to a text file. 然后可以将其写入文本文件。 I gave up trying to use pickle as I was getting errors telling me to write integers to a .dat file. 我遇到错误并告诉我将整数写入.dat文件时,我放弃尝试使用pickle。 I apologise for not using pickle. 很抱歉没有使用泡菜。