82

我是第一次学习对象序列化。我尝试阅读和“谷歌搜索”以了解泡菜和搁置模块的差异,但我不确定我是否理解它。什么时候用哪一个?Pickle 可以将每个 python 对象转换为可以保存到文件中的字节流。那为什么我们需要模块搁置?泡菜不是更快吗?

4

2 回答 2

110

pickle用于将某些对象(或多个对象)序列化为文件中的单个字节流。

shelve构建pickle并实现了一个序列化字典,其中对象被腌制,但与键(某些字符串)相关联,因此您可以加载搁置的数据文件并通过键访问腌制对象。如果您要序列化许多对象,这可能会更方便。

这是两者之间的使用示例。(应该在最新版本的 Python 2.7 和 Python 3.x 中工作)。

pickle例子

import pickle

integers = [1, 2, 3, 4, 5]

with open('pickle-example.p', 'wb') as pfile:
    pickle.dump(integers, pfile)

这会将integers列表转储到一个名为pickle-example.p.

现在尝试读回腌制文件。

import pickle

with open('pickle-example.p', 'rb') as pfile:
    integers = pickle.load(pfile)
    print integers

以上应输出[1, 2, 3, 4, 5].

shelve例子

import shelve

integers = [1, 2, 3, 4, 5]

# If you're using Python 2.7, import contextlib and use
# the line:
# with contextlib.closing(shelve.open('shelf-example', 'c')) as shelf:
with shelve.open('shelf-example', 'c') as shelf:
    shelf['ints'] = integers

请注意您如何通过类似字典的访问将对象添加到架子上。

使用如下代码读回对象:

import shelve

# If you're using Python 2.7, import contextlib and use
# the line:
# with contextlib.closing(shelve.open('shelf-example', 'r')) as shelf:
with shelve.open('shelf-example', 'r') as shelf:
    for key in shelf.keys():
        print(repr(key), repr(shelf[key]))

输出将是'ints', [1, 2, 3, 4, 5].

于 2010-11-05T03:47:50.270 回答
4

根据泡菜文档:

序列化是一个比持久化更原始的概念。虽然pickle读写文件对象,但它不处理命名持久对象的问题,也不处理(甚至更复杂的)持久对象的并发访问问题。pickle模块可以将复杂的对象转换为字节流,并且可以将字节流转换为具有相同内部结构的对象。也许对这些字节流最明显的事情是将它们写入文件,但也可以通过网络发送它们或将它们存储在数据库中。shelve模块提供了一个简单的接口,用于在 DBM 样式的数据库文件中腌制和取消腌制对象

于 2020-01-27T21:24:59.720 回答