數(shù)據(jù)讀寫
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 # 不能改變單個(gè)條目的值
print(db['key1'])
db['key1'] = {'1':'a', '2':'b', '3':'c'} # 可以覆蓋整個(gè)key的值
print(db['key1'])
db.close()
db = sv.open('db', writeback = True)
print(db['key1'])
db['key1']['1'] = 10 # 可以改變單個(gè)條目的值
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()
輸入結(jié)果
{'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}
總結(jié):
- 從shelve的db文件中重新再訪問(wèn)一個(gè)key拿的是它的拷貝研乒!
修改此拷貝后不做拷貝寫回并不影響原來(lái)的key婿滓,
但你要是直接做的操作是賦值新的值到一個(gè)key里,那肯定就是指向原來(lái)的key躬柬,會(huì)被覆蓋的。 - writeback=True肴捉,DB在close()的時(shí)候會(huì)將緩存中的每一個(gè)對(duì)象都寫入到DB
open()參數(shù)說(shuō)明
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 |