Home >Backend Development >Python Tutorial >python shelve module
shelve
shelve is a simple data storage solution. It has only one function, which is open(). This function receives a parameter, which is the file name, and then returns a shelf object. You can use it to store things, and you can simply It is treated as a dictionary. When you finish storing it, call the close function to close it. This has a potential small problem, as follows:
[python] view plaincopy
>>> import shelve
>> > s = shelve.open('test.dat')
>>> s['x'] = ['a', 'b', 'c']
>>> s[ 'x'].append('d')
>>> s['x']
['a', 'b', 'c']
Where did the stored d go? In fact, it is very simple. d does not write back. You save ['a', 'b', 'c'] to x. When you read s['x'] again, s['x'] is just a Copy, and you did not write the copy back, so when you read s['x'] again, it read a copy from the source, so your newly modified content will not appear in the copy. , the solution is, the first one is to use a cached variable, as shown below
[python] view plaincopy
>>> temp = s['x']
>>> temp.append ('d')
>>> s['x'] = temp
>>> s['x']
['a', 'b', 'c', 'd' ]
There is another method in python2.4, which is to assign the value of the writeback parameter of the open method to True. In this case, all the content after you open will be in the cache. When you close, it will be all at once. written to the hard drive. This is recommended if the amount of data is not very large.
The following is the code for a simple database based on shelve
[python] view plaincopy
#database.py
import sys, shelve
def store_person(db):
"""
Query user for data and store it in the shelf object
""" pid = raw_input('Enter unique ID number: ')
person = {}
person['name'] = raw_input('Enter name: ')
person['age'] = raw_input( 'Enter age: ')
person['phone'] = raw_input('Enter phone number: ') db[pid] = person
def lookup_person(db):
"""
Query user for ID and desired field , and fetch the corresponding data from
the shelf object
"""
pid = raw_input('Enter ID number: ')
field = raw_input('What would you like to know? (name, age, phone) ')
field = field.strip().lower()
print field.capitalize() + ':',
db[pid][field]
def print_help():
print 'The available commons are: '
print ' store :Stores information about a person'
print 'lookup :Looks up a person from ID number'
print 'quit :Save changes and exit'
print '? rint this message'
def enter_command(): cmd = raw_input ('Enter command (? for help): ')
cmd = cmd.strip().lower()
return cmd
def main():
database = shelve.open('database.dat') try:
cmd elif cmd == 'lookup':
lookup_person(database)
elif cmd == '?':
print_help()
elif cmd == 'quit':
return
finally:
database.close()
if __name__ == '__main__': main()