pickle and Shelve和有什么不一样? [英] What is the difference between pickle and shelve?

查看:306
本文介绍了pickle and Shelve和有什么不一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning about object serialization for the first time. I tried reading and 'googling' for differences in the modules pickle and shelve but I am not sure I understand it. When to use which one? Pickle can turn every python object into stream of bytes which can be persisted into a file. Then why do we need the module shelve? Isn't pickle faster?

推荐答案

pickle用于将一个或多个对象序列化为文件中的单个字节流.

pickle is for serializing some object (or objects) as a single bytestream in a file.

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

shelve builds on top of pickle 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.

这里是两者之间用法的一个例子. (应该在最新版本的python 2.7和python 3.x中工作).

Here is an example of usage between the two. (should work in latest versions of Python 2.7 and Python 3.x).

import pickle

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

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

这会将integers列表转储到名为pickle-example.p的二进制文件中.

This will dump the integers list to a binary file called pickle-example.p.

现在尝试回读腌制过的文件.

Now try reading the pickled file back.

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

请注意如何通过类似字典的访问将对象添加到书架中.

Notice how you add objects to the shelf via dictionary-like access.

使用如下代码重新读取对象:

Read the object back in with code like the following:

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

这篇关于pickle and Shelve和有什么不一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆