泡菜和搁置之间有什么区别?
-
29-09-2019 - |
题
我是第一次学习对象序列化。我尝试阅读和“谷歌搜索”以了解模块腌制和搁置的差异,但我不确定我理解。什么时候使用哪一个?泡菜可以将每个python对象变成可以持续到文件中的字节流。那为什么我们需要模块搁置呢?泡菜不是更快吗?
解决方案
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]
.
不隶属于 StackOverflow