🐍 Python - shelve
Updated at 2018-06-10 22:07
shelve
is a dictionary-like object that can be saved to disk in a binary format. Values can be anything that can be pickled.
import os
import shelve
DB_FILE = './what.shelve'
# .open() will create the file if it doesn't exist
with shelve.open(DB_FILE) as db:
db['owner'] = 'Ruksi'
db['people'] = []
# by default, stuff is written ONLY on assignment
# not when a mutable variable e.g. list is changed
temp = db['people']
temp.append({'name': 'John'})
db['people'] = temp
with shelve.open(DB_FILE) as db:
assert db['owner'] == 'Ruksi'
assert db['people'] == [{'name': 'John'}]
with shelve.open(DB_FILE) as db:
del db['owner']
del db['people']
try:
os.remove(DB_FILE)
except OSError:
pass
Sources
- Fluent Python, Luciano Ramalho