Shelve module
Shelve is similar to a key-value database, which can be conveniently used to hold Python's memory objects, using pickle to serialize data internally, and simply, users can save a list, dictionary, or user-defined class instance to shelve. The next time you need to use it, just take it out, it's a Python memory object.
Use Example 1
Import Shelvezhang = Dict ([' Name ', ' age '], [' Zhang ',])) Li = Dict ([' Name ', ' age '], [' Li ', 15]) # Store object to file db = She Lve.open (' shelvedict.db ') # Open a file db[' zhang ' = Zhang # Add content to the file, add the same as the key value pair to the dictionary db[' li ') = Lidb.close () # Close File # Extract object from File db = Shelve.open (' shelvedict.db ') # Open a file print (db[' Zhang ') # Read the same as the key obtained from the dictionary {' name ': ' Zhang ', ' Age ': 14}print (db[' li ') # results for {' age ': ' name ': ' li '}# extract the object from the file and modify the db = Shelve.open (' shelvedict.db ') # Open File Zhang_obj = db[' Zhang ') # Read the previously stored object from the file zhang_obj[' name '] = ' Zi ' # directly modify the object zhang_obj[' age ' = 24db[' Zhang '] = zhang_obj # re-stored in the dictionary file object in print (db[' Zhang ') # The result is as follows {' Age ': ' ' name ': ' Zi '}db.close ()
Use Example 2
Import Shelveclass Shelveutil (object): "" " use shelve store to extract Object" "" def __init__ (self, file): Self.file_obj = Shelve.open (file) def save (self, Key, value): "" " Storage object :p Aram key: :p Aram value:< C10/>:return: "" " Self.file_obj[key] = value def load (self, key):" " gets object :p Aram Key : : Return: "" " return Self.file_obj[key] def __del__ (self): self.file_obj.close () if __ name__ = = ' __main__ ': a = {' A ': 1, ' B ': 2} s = Shelveutil (' a.db ') s.save (' A ', a) print (S.load (' a '))
Python shelve module