Shelve module is a simple k,v memory data through the file persisted module, can persist any pickle can support the Python data format , He only one function is open (), this function receives a parameter is the file name, Then return a shelf object, you can use him to store things, you can simply think of him as a dictionary, when you have finished storing, call the close function to close.
>>> Import shelve
>>> sfile = Shelve.open (' shelve_test ') # Open a file
>>> sfile[' k1 ' = [' A ', ' B '] # persistent storage list
>>> sfile[' K1 ']
[' A ', ' B ']
>>> sfile.close () # File Close
Pickle is stored or read as follows:
converts a string into a string that only Python can recognize in a file
>>> Import Pickle
>>> pw = open (' Test ', ' WB ')
>>> Pw.write (Pickle.dumps ([' A ', ' B '])
>>> Pw.close ()
Convert A string to the original data form via Pickle.load
>>> PR = open (' Test ', ' RB ')
>>> PRF = pickle.load (pr)
>>> PRF
[' A ', ' B ']
But now I want to persist the list of stored operations, such as add, delete, data, and so on, so shelve and pickle can do so?
>>> Import Shelve
>>> sfile = Shelve.open (' shelve_test ')
>>> sfile[' k1 '] = [' A ', ' B ']
>>> sfile[' K1 '].append (' C ')
>>> sfile[' K1 ']
[' A ', ' B ']
Where did the stored C go? Actually very simple, C did not write back, you put [' A ', ' B '] to K1, when you read sfile[' K1 '], sfile[' K1 ' is just a copy, and you do not write back, so when you read the s[' X ' again, it read a copy from the source,
So, your newly modified content does not appear in the copy, the solution is that the first one is to take advantage of a cached variable, but this can only be applied to a
Object, the face of multiple objects is helpless:
>>> tmp = sfile[' K1 ']
>>> tmp.append (' C ')
>>> sfile[' k1 ' = tmp
>>> sfile[' K1 ']
[' A ', ' B ', ' C ']
>>> sfile[' k2 '] = [' 1 ', ' 2 ']
>>> sfile[' K2 '].append (' 3 ')
>>> sfile[' K2 ']
[' 1 ', ' 2 ']
So how can you fundamentally achieve the effect I want? Hey! There's a way that just mentioned C didn't write back if let all more
Change the data to write back not to be able to achieve effect, that is writeback, set writeback to True, see effect:
>>> sfile = Shelve.open (' shelve_test ')
>>> Sfile.writeback = True
>>> sfile[' K1 ']
[' A ', ' B ', ' C ']
>>> sfile[' K1 '].append (' d ')
>>> sfile[' K1 ']
[' A ', ' B ', ' C ', ' d ']
>>> sfile[' k2 '] = [' 1 ', ' 2 ']
>>> sfile[' K2 ']
[' 1 ', ' 2 ']
>>> sfile[' K2 '].append (' 3 ')
>>> sfile[' K2 ']
[' 1 ', ' 2 ', ' 3 ']
This article is from the "a myriad of simple pleasures of technology to enjoy" blog, please be sure to keep this source http://51enjoy.blog.51cto.com/8393791/1743984
Shelve vs. Pickle