Python学习基础笔记四十三——shelve序列化

shelve:也是Python提供给我们的序列化工具,比pickle使用起来还简单。

shelve只提供给我们一个open方法,是用key来访问的,使用起来和字典类似。

案例:

import shelve

f = shelve.open('shelve_file')
f['key1'] = {'int': 10, 'float': 9.5, 'string': 'Sample data'}
f['key2'] = 'String'
f['key3'] = [1, 2, 3]
f['key4'] = 12345
f.close()

f1 = shelve.open('shelve_file')
content1 = f1['key1']
content2 = f1['key2']
content3 = f1['key3']
content4 = f1['key4']
print(content1)
print(content2)
print(content3)
print(content4)
f1.close()

结果:

Python学习基础笔记四十三——shelve序列化_第1张图片

我们再看下shelve保存的文件:

Python学习基础笔记四十三——shelve序列化_第2张图片

shelve存储的文件内容是不透明的。

shelve模块是有限制的,它不支持多个应用同一个时间往同一个文件(db)中写操作,所以当我们知道我们的应用如果只是进行读操作,我们可以让shelve通过只读的方式打开文件。

import shelve

# f1 = shelve.open('shelve_file')
# f['key'] = {'int': 10, 'float': 9.5, 'string': 'Sample data'}
# print(f1['key'])
#
# f1.close()

f2 = shelve.open('shelve_file', writeback=True)
print(f2['key'])
f2['key']['new_value'] = 'this was not here before.'
f2.close()

f3 = shelve.open('shelve_file')
print(f3['key'])
f3.close()

由于shelve在默认的情况下是不会记录待持久化对象的任何修改的,所以我们在shelve.open()时候需要修改默认参数,否则对象的修改不会保存。

writeback方式有优点也有缺点,优点是减少了我们出错的效率,并且让对象的持久化对用户更加地透明了。但这种方式并不是所有的情况下都需要的。

你可能感兴趣的:(Python,python)