Ще приклади
Створюємо файл бази даних:import shelve s = shelve.open('test_shelf.db')try: s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }finally: s.close()Доступ до даних створеного файла:
import shelve s = shelve.open('test_shelf.db')try: existing = s['key1']finally: s.close() print existingПісля виконання скрипта побачимо:
$ python shelve_create.py$ python shelve_existing.py {'int': 10, 'float': 9.5, 'string': 'Sample data'}Доступ для змін можна заборонити:.
import shelve s = shelve.open('test_shelf.db', flag='r')try: existing = s['key1']finally: s.close() print existingОбновлення даних файлу
import shelve s = shelve.open('test_shelf.db')try: print s['key1'] s['key1']['new_value'] = 'this was not here before'finally: s.close() s = shelve.open('test_shelf.db', writeback=True)try: print s['key1']finally: s.close()В цьому прикладі зміна значення за ключом ‘key1’ не буде збережена.
$ python shelve_create.py$ python shelve_withoutwriteback.py {'int': 10, 'float': 9.5, 'string': 'Sample data'}{'int': 10, 'float': 9.5, 'string': 'Sample data'}Скористаємось для збереження змін у записі опцією writeback. Всі зміни в записах заносятся до файлу коли він закривається.
import shelve s = shelve.open('test_shelf.db', writeback=True)try: print s['key1'] s['key1']['new_value'] = 'this was not here before' print s['key1']finally: s.close() s = shelve.open('test_shelf.db', writeback=True)try: print s['key1']finally: s.close()
Підсумуємо:
Занаесення даних до файлу:
importshelve
flights = {"1":"A", "2":"B", "3":"C"}
times = ["230pm", "320pm", "420pm"]
db = shelve.open("shelved.dat", "n")
db['flights'] = flights
db['times'] = times
print db.keys()
db.close()
f = open("shelved.dat", "r")
data = f.read()
print data
f.close()
# Retrieving Objects froma Shelve File
db = shelve.open("shelved.dat", "r")
fork in db.keys():
obj = db[k]
print "%s: %s" % (k, obj)
flightDB = db['flights']
flights = flightDB.keys()
cities = flightDB.values()
times = db['times']
x = 0
forflight in flights:
print ("Flight %s leaves for %s at %s" % (flight, cities[x], times[x]))
x+=1
db.close()
Перевірка занесення
importshelve
s = shelve.open('test.dat')
s['x'] = ['a', 'b', 'c']
s['x'].append('d')
print s['x']
temp = s['x']
temp.append('d')
s['x'] = temp
print s['x']
Обновлення даних
importshelve
newtimes = ["110pm", "220pm", "300pm", "445pm"]
db = shelve.open("shelved.dat", "w", writeback=1)
fork in db.keys():
obj = db[k]
print "%s: %s" % (k, obj)
flights = db['flights']
times = db['times']
flights['1145'] = "Dallas"
flights['1709'] = "Orlando"
db['times'] = newtimes
db['oldtimes'] = times
db.sync()
fork in db.keys():
obj = db[k]
print "%s: %s" % (k, obj)
db.close()