Shelve
If you only need a simple storage solution, then the shelve module will meet most of your needs, and all you need is to provide it with a file name. The only interesting function in shelve is open, which returns a shelf object when called
Attention:
Just use it as a normal dictionary (but the key must be a string) to manipulate it.
After the operation is finished, call its Close method
In the version after python2.4 , there is a solution that sets the writeback parameter of the Open function to True. This allows all data structures that are read from shelf or assigned to shelf to be stored in memory (cache) and written back to the hard disk only when the shelf is turned off.
Open function Parameter description
This is mainly to solve this problem:
1 Importshelve2s = Shelve.open ('Data.dat','C', None,false)3s['x'] = ['a','b','C']4s['x'].append ('D')5 Print(s['x'])
Will find s[' x ' or ' A ', ' B ', ' C ' this is because in s['x'].append ('d') there is a procedure for creating a replica that extracts the contents of the s[' X '] first to make a copy, and then appends the ' d ' to the copy, but the changes are not synchronized in s[' x '.
So the solution is so broad
1 Importshelve2s = Shelve.open ('Data.dat','C', None,false)3s['x'] = ['a','b','C']4temp = s['x']! 5Temp.append ('D')! 6s['x'] =Temp! 7 Print(s['x'])
The highlights of this section are mainly in s['x'] = temp equivalent to a write-back operation , so that the changed data is written to s[' X ']
Example
Finally there is a personal information entry/viewing program in the back
Added a procedure for testing whether to repeat when adding information
1 ImportSys,shelve2 #储存信息3 defStore_person (db):4 while(True):5PID = input ('Enter Unique ID number:')6 ifPidinchDb.keys ():7 Print('find the same key:')8 Else:9 BreakTen Oneperson = {} Aperson ['name'] = input ('Enter Name:') -person [' Age'] = input ('Enter Age:') -person ['Phone'] = input ('Enter phone Number:') the -Db[pid] = Person - Print('add to DB done!') -#查找信息 + defLookup_person (db): -PID = input ('Enter ID Number:') +field = input ('What would do you like to know? (Name,age,phone,all):') Afield =Field.strip (). Lower () at iffield = =' All': -D =Db[pid] - forKey,valueinchD.items (): - Print(Key,':', value) - Else: - Print(Field.capitalize () +':', Db[pid][field]) in#。。。 - defprint_help (): to Print('Help something') + -#获取用户输入 the defEnter_command (): *cmd = input ('Enter command (? For help):') $cmd =Cmd.strip (). Lower ()Panax Notoginseng returncmd - the defMain (): +Database = Shelve.open ('Date.dat') A Try: the whileTrue: +cmd =Enter_command () - ifcmd = ='s': $ Store_person (database) $ elifcmd = ='L': - Lookup_person (database) - elifcmd = ='?': the print_help () - elifcmd = ='Q':Wuyi Break; the finally: - database.close () Wu Print('Stop by User') - About if __name__=='__main__': Main ()
Python Brief standard library (3)