The code shows you how to create a persistent to file dictionary of data using the python module shelve.
Persistent to file dictionary using Python module shelve
Gribouillis commented: useful! +14
''' Shelve_test2.py
use a dictionary object and module shelve
to create a 'persistent to file' dictionary
Python2 creates a single (24kb) file 'phonebook.slv'
Python3 creates 3 much smaller (about 1kb each) files:
'phonebook.slv.dir'
'phonebook.slv.dat'
'phonebook.slv.bak'
Tested with Python27 and Python33 by vegaseat 04sep2013
'''
import shelve
# name shelve byte stream data file
# works with Python2 annd Python3
data_file = 'phonebook.slv'
# open existing shelve file or create new shelve file
sh = shelve.open(data_file)
# a simple dictionary of name:phone pairs
phonebook = {
'Andrew Parson': '880-6336',
'Emily Everett': '678-4346',
'Peter Power': '765-8344',
'Lewis Lame': '112-2345'
}
# this will save all current phonebook data
# the access key will be "myphone_dict" (you pick name)
sh["myphone_dict"] = phonebook
# do one more dictionary entry ...
phonebook['Ginger Roger'] = '123-4567'
# you can update and save again before you close
sh["myphone_dict"] = phonebook
# close when done
sh.close()
# testing ...
# open the shelve file again for further work
# remember the access key is "myphone_dict"
sh = shelve.open(data_file)
phonebook2 = sh["myphone_dict"]
# can add another dictionary entry
phonebook2['Larry Lark'] = '923-4568'
# save the current phonebook data to the shelve file
sh["myphone_dict"] = phonebook2
# close when done
sh.close()
print('-'*30)
# test the contents ...
# retrieve the saved data from the file
sh = shelve.open('phonebook.slv')
phonebook3 = sh["myphone_dict"]
# print the contents
for name, phone in sorted(phonebook3.items()):
print( "%-20s %s" % (name, phone) )
print('-'*30)
# close when done
sh.close()
''' result ...
------------------------------
Andrew Parson 880-6336
Emily Everett 678-4346
Ginger Roger 123-4567
Larry Lark 923-4568
Lewis Lame 112-2345
Peter Power 765-8344
------------------------------
'''
Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.