python - pickle 和搁置有什么区别?

标签 python object pickle shelve object-serialization

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

最佳答案

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

shelve 构建在 pickle 之上,并实现了一个序列化字典,其中对象被 pickle ,但与一个键(一些字符串)相关联,因此您可以加载搁置的数据文件并通过 key 访问您的 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 的二进制文件中。

现在尝试读回 pickle 文件。

import pickle

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

上面应该输出[1, 2, 3, 4, 5]

搁置示例

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]

关于python - pickle 和搁置有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4103430/

相关文章:

python - 允许谷歌应用程序的权限后无法连接到本地主机

python - Python While 循环中的赋值条件

javascript - ReactJS:循环对象

python - 确定为什么一个对象不能被 pickle

python - 将 Pickled 数据发送到 Graphite

python - 如何解决 UnboundLocalError?

python - dnspython动态更新PeerBadKey

c++ - 无论对象变量类型如何,如何对对象数组进行排序

PHP 计算对象属性出现次数

python - pickle.dump 由于 GIL 而阻塞多线程 python 应用程序中的主线程