Python3 shelve用法

数据读写

import shelve as sv

db = sv.open('db')
db['key1'] = {'1':1, '2':2, '3':3}
db.close()

db = sv.open('db')
print(db['key1'])
db['key1']['1'] = 10 # 不能改变单个条目的值
print(db['key1'])
db['key1'] = {'1':'a', '2':'b', '3':'c'} # 可以覆盖整个key的值
print(db['key1'])
db.close()

db = sv.open('db', writeback = True)
print(db['key1'])
db['key1']['1'] = 10 # 可以改变单个条目的值
print(db['key1'])
db['key2'] = {'a':100, 'b':200, 'c':300}
db.close()

db = sv.open('db')
print(db['key1'])
print(db['key2'])
db.close()

输入结果

{'1': 1, '2': 2, '3': 3}
{'1': 1, '2': 2, '3': 3}
{'1': 'a', '2': 'b', '3': 'c'}
{'1': 'a', '2': 'b', '3': 'c'}
{'1': 10, '2': 'b', '3': 'c'}
{'1': 10, '2': 'b', '3': 'c'}
{'a': 100, 'b': 200, 'c': 300}

总结:

  1. 从shelve的db文件中重新再访问一个key拿的是它的拷贝!
    修改此拷贝后不做拷贝写回并不影响原来的key,
    但你要是直接做的操作是赋值新的值到一个key里,那肯定就是指向原来的key,会被覆盖的。
  2. writeback=True,DB在close()的时候会将缓存中的每一个对象都写入到DB

open()参数说明

shelve.open(filename, flag='c', protocol=None, writeback=False)

The optional flag argument can be:

Value Meaning
'r' Open existing database for reading only (default)
'w' Open existing database for reading and writing
'c' Open database for reading and writing, creating it if it doesn’t exist
'n' Always create a new, empty database, open for reading and writing

你可能感兴趣的:(Python3 shelve用法)