我如何使用泡菜保存字典?
我浏览了Python文档给出的信息,但我仍然有点困惑。 有人可以发布示例代码来写一个新文件,然后使用pickle将字典转储到它吗?
尝试这个:
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
import pickle
your_data = {'foo': 'bar'}
# Store data (serialize)
with open('filename.pickle', 'wb') as handle:
pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Load data (deserialize)
with open('filename.pickle', 'rb') as handle:
unserialized_data = pickle.load(handle)
print(your_data == unserialized_data)
HIGHEST_PROTOCOL
的优点是文件变小。 这使得有时候可以快速取出。
重要提示 :腌菜的最大文件大小约为2GB。
备择方案
对于您的应用程序,以下内容可能很重要:
另请参阅:比较数据序列化格式
如果您正在寻找制作配置文件的方式,您可能需要阅读我的简短文章Python配置文件
# 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"}
链接地址: http://www.djcxy.com/p/48693.html
上一篇: How can I use pickle to save a dict?
下一篇: 8 texts in json.dumps as UTF8, not as \u escape sequence