zub*_*hta 61 python object shelve pickle object-serialization
我是第一次学习对象序列化.我尝试阅读和"谷歌搜索"模块泡菜和搁置的差异,但我不确定我理解它.什么时候使用哪一个?Pickle可以将每个python对象转换为可以保存到文件中的字节流.那为什么我们需要模块搁置?泡菜不快吗?
wkl*_*wkl 82
pickle 用于将某些对象(或对象)序列化为文件中的单个字节流.
shelve构建在pickle一个序列化字典之上并实现一个序列化字典,其中对象被pickle,但与一个键(某个字符串)相关联,因此您可以加载搁置的数据文件并通过键访问您的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)
Run Code Online (Sandbox Code Playgroud)
这会将integers列表转储到名为的二进制文件中pickle-example.p.
现在尝试回读pickle文件.
import pickle
with open('pickle-example.p', 'rb') as pfile:
integers = pickle.load(pfile)
print integers
Run Code Online (Sandbox Code Playgroud)
以上应该输出[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
Run Code Online (Sandbox Code Playgroud)
请注意如何通过类似字典的访问将对象添加到工具架.
使用以下代码重新读取对象:
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])))
Run Code Online (Sandbox Code Playgroud)
输出将是'ints', [1, 2, 3, 4, 5].
| 归档时间: |
|
| 查看次数: |
23599 次 |
| 最近记录: |