The function that is useful in shelve is open (), but the call path in the database function written below is often wrong, and if you call a file that has never been used, it will run normally, for the time being no reason is found.
Calling Shelve.open () returns a shelf object to store the content as a normal dictionary to store the data (the dictionary key must be a string), and the close () function is called after the storage is complete to close the file.
Note In order to properly modify the stored object using the Shelve module, you must bind the temporary variable to the obtained copy and re-store the copy after modification. Alternatively, set the writeback parameter in the open () directly to true.
The following is a small database built using the shelve module
1 #Encoding=utf-82 __author__='Heng'3 #a simple database application4 5 Importsys, shelve6 7 defStore_person (db):8 """9 Query user for data and store it in the shelf objectTen """ OnePID = Raw_input ('Enter Unique ID number:') Aperson = {} -person['name'] = Raw_input ('Enter Name:') -person[' Age'] = Raw_input ('Enter Age:') theperson['Phone'] = Raw_input ('Enter phone Number:') -Db[pid] = Person - - defLookup_person (db): + """ - Query user for ID and desired field, and fetch the corresponding data from + The Shelf Object A """ atPID = Raw_input ('Enter ID Number:') -field = Raw_input ('What would do you like to know? (name, age, phone)') -field =Field.strip (). Lower () - PrintField.capitalize () +':', - Db[pid][field] - in defprint_help (): - Print 'The available Commons is:' to Print 'store:stores information about a person' + Print 'lookup:looks up a person from ID number' - Print 'quit:save changes and exit' the Print '? :P rint This message' * $ defEnter_command ():Panax Notoginsengcmd = Raw_input ('Enter command (? For help):') -cmd =Cmd.strip (). Lower () the returncmd + A defMain (): theDatabase = Shelve.open ('Testdata.dat') + Try: - whileTrue: $cmd =Enter_command () $ ifcmd = ='Store': - Store_person (database) - elifcmd = ='Lookup': the Lookup_person (database) - elifcmd = ='?':Wuyi print_help () the elifcmd = ='quit': - return Wu finally: - database.close () About if __name__=='__main__': Main ()
The shelve module in Python