泡菜和架子有什么区别?

问题描述 投票:61回答:2

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

python object pickle shelve object-serialization
2个回答
82
投票

[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]


0
投票

根据pickle文档:

串行化是一个比持久性更原始的概念;尽管pickle读写文件对象,但是它不能处理持久对象的命名问题,也不能处理(甚至更复杂的)并发访问持久对象的问题。 pickle模块可以将复杂的对象转换为字节流,并且可以将字节流转换为具有相同内部结构的对象。也许与这些字节流有关的最明显的事情是将它们写入文件,但是也可以考虑通过网络发送它们或将它们存储在数据库中。 shelve模块提供了一个简单的界面来对DBM样式的数据库文件中的对象进行腌制和解腌。

© www.soinside.com 2019 - 2024. All rights reserved.