Using shelve is quite easy and intuitive.
First, let's import the appropriate module and create an object representing a file-based database:
import shelve
my_shelve = shelve.open('first_shelve.shlv', flag='w')
The meaning of the optional flag parameter:
Value | Meaning |
---|---|
'r' | Open existing database for reading only |
'w' | Open existing database for reading and writing |
'c' | Open database for reading and writing, creating it if it doesn’t exist (this is a default value) |
'n' | Always create a new, empty database, open for reading and writing |
Now our shelve object is ready for action, so let's insert a few items and close the shelve object.
my_shelve['USD'] = {'code':'US dollar', 'symbol': '$'}
my_shelve['JPY'] = {'code':'Japanese yen', 'symbol': '¥'}
my_shelve.close()
Now let's open the shelve file to demonstrate direct access to the elements (contrary to the sequential access to items when we use pickles).
new_shelve = shelve.open(shelve_name)
print(new_shelve['USD'])
new_shelve.close()
The final code is presented in the right pane.
Code
import shelveshelve_name = 'first_shelve.shlv'
my_shelve = shelve.open(shelve_name, flag='c')
my_shelve['EUR'] = {'code':'Euro', 'symbol': '€'}
my_shelve['GBP'] = {'code':'Pounds sterling', 'symbol': '£'}
my_shelve['USD'] = {'code':'US dollar', 'symbol': '$'}
my_shelve['JPY'] = {'code':'Japanese yen', 'symbol': '¥'}
my_shelve.close()
new_shelve = shelve.open(shelve_name)
print(new_shelve['USD'])
new_shelve.close()
{{ dockerServerErrorMsg }}
×
{{ errorMsg }}
×
{{ successMsg }}
×