Python之shelve模块的使用

 1、创建一个shelve模块的数据存储结构

#!/usr/bin/env python3
# encoding: utf-8

import shelve

with shelve.open('test_shelve.db') as sl:
    sl['key1'] = {
        'int': 10,
        'float': 9.8,
        'string': 'Hello World'
    }
shelve_create.py

运行效果

[root@python-mysql mnt]# python3 shelve_create.py 

[root@python-mysql mnt]# ll
-rw-r--r-- 1 root root 198 Jan 12 15:13 shelve_create.py
-rw-r--r-- 1 root root  16 Jan 12 15:13 test_shelve.db.bak #自动生成
-rw-r--r-- 1 root root  72 Jan 12 15:13 test_shelve.db.dat #自动生成
-rw-r--r-- 1 root root 16 Jan 12 15:13 test_shelve.db.dir #自动生成

 2、读取shelve模块数据存储结构

#!/usr/bin/env python3
# encoding: utf-8

import shelve

with shelve.open('test_shelve.db') as sl:
    existing = sl['key1']
print(existing)
shelve_existing.py

运行效果

[root@python-mysql mnt]# python3 shelve_existing.py 
{'int': 10, 'float': 9.8, 'string': 'Hello World'}

 3、shelve模块设置只读模式<测试Python 3.6.6 版本该功能失效,升级为Python3.8.1正常使用>

#!/usr/bin/env python3
# encoding: utf-8

import dbm
import shelve

with shelve.open('test_shelve.db',flag='r',writeback=False) as s:
    print('Existing:', s['key1'])
    try:
        s['key1'] = 'new value'
    except dbm.error as err:
        print('ERROR: {}'.format(err))
shelve_readonly.py

运行效果

[root@python-mysql mnt]# python3.8 shelve_readonly.py 
Existing {'int': 10, 'float': 9.8, 'string': 'Hello World'}
错误:The database is opened for reading only

 4、shelve模块默认是没有回写的示例

#!/usr/bin/env python3
# encoding: utf-8

import shelve

with shelve.open('test_shelve.db') as sl:
    print(sl['key1'])
    sl['key1']['new_key'] = '设置二级key值'

with shelve.open('test_shelve.db', writeback=True) as sl:
    print(sl['key1'])
shelve_withoutwriteback.py

运行效果

[root@python-mysql mnt]# python3 shelve_withoutwriteback.py
{'int': 10, 'float': 9.8, 'string': 'Hello World'} #没有修改数据
{'int': 10, 'float': 9.8, 'string': 'Hello World'}

 5、shelve模块设置回写的示例

#!/usr/bin/env python3
# encoding: utf-8

import shelve

with shelve.open('test_shelve.db', writeback=True) as sl:
    print(sl['key1'])
    sl['key1']['new_key'] = '设置二级key值'

with shelve.open('test_shelve.db', writeback=True) as sl:
    print(sl['key1'])
shelve_writeback.py

 运行效果

[root@python-mysql mnt]# python3 shelve_writeback.py
{'int': 10, 'float': 9.8, 'string': 'Hello World'}
{'int': 10, 'float': 9.8, 'string': 'Hello World', 'new_key': '设置二级key值'}

你可能感兴趣的:(Python之shelve模块的使用)