泡菜和货架有什么区别?
什么时候适合使用pickle
,什么时候适合使用shelve
?也就是说,他们的做法有何不同?
根据我的研究,我了解到 pickle 可以将每个 Python 对象转换为可以保存到文件中的字节流。那为什么我们还需要shelve
呢? pickle
不是更快吗?
When is it appropriate to use pickle
, and when is it appropriate to use shelve
? That is to say, what do they do differently from each other?
From my research, I understood that pickle
can turn every Python object into stream of bytes which can be persisted into a file. Then why do we need shelve
as well? Isn't pickle
faster?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
pickle
用于将某些对象(或多个对象)序列化为文件中的单个字节流。shelve
构建在pickle
之上,并实现一个序列化字典,其中对象被腌制,但与键(某个字符串)相关联,因此您可以加载搁置的数据文件并访问通过按键腌制的对象。如果您要序列化许多对象,这可能会更方便。这是两者之间的用法示例。 (应该适用于最新版本的 Python 2.7 和 Python 3.x)。
pickle
示例这会将
integers
列表转储到名为pickle-example.p
的二进制文件中。现在尝试读回腌制的文件。
上面应该输出
[1, 2, 3, 4, 5]
。shelve
示例请注意如何通过类似字典的访问将对象添加到架子中。
使用如下代码读回对象:
输出将为
'ints', [1, 2, 3, 4, 5]
。pickle
is for serializing some object (or objects) as a single bytestream in a file.shelve
builds on top ofpickle
and implements a serialization dictionary where objects are pickled, but associated with a key (some string), so you can load your shelved data file and access your pickled objects via keys. This could be more convenient were you to be serializing many objects.Here is an example of usage between the two. (should work in latest versions of Python 2.7 and Python 3.x).
pickle
ExampleThis will dump the
integers
list to a binary file calledpickle-example.p
.Now try reading the pickled file back.
The above should output
[1, 2, 3, 4, 5]
.shelve
ExampleNotice how you add objects to the shelf via dictionary-like access.
Read the object back in with code like the following:
The output will be
'ints', [1, 2, 3, 4, 5]
.根据 pickle 文档:
According to pickle documentation: