Then, Don't Forget To Check Our Index Because their You can find really many interesting stuff.
So, let's start our Tutorial.
shelve_part_1 slides
In [1]:
# # ================================================== # PYTHON SHELVE MODULE TUTORIAL # ================================================== # # author : suraj singh bisht # contact : # surajsinghbisht054@gmail.com # https://www.bitforestinfo.com # # Here, For This Tutorial # # I am using # # Operating System : Ubuntu 16.04 # Python Version : python 2.7.12 # Editor : ipython notebook #
In [2]:
# # Importing Modules # importshelve# shelve : for database api
importpprint# pprint : for printing objects
In [3]:
# # db_name = Name Of Database. # # You Can Use Any Name What You Want! # db_name="example_database_shelve.db"
In [4]:
# # Open Database And Create Shelve Object handler. # Shelve Object handler Is Very Easy To Use. # because shelve completely works like a # dictonery object. # db=shelve.open(db_name)
In [5]:
# # Creating A List Only For Exmaple Purpose # storelist=["Dog", "cat", "rat", "snake", "kite"]
In [6]:
# # Print Example List # pprint.pprint(storelist)
['Dog', 'cat', 'rat', 'snake', 'kite']
In [7]:
# # Create Example Dictonery # storedict={"rat":"cat", "cat":"dog", "dog":"wolf", "wolf":"lion"}
# # Storelist In Database. # db['store_list']=storelist
In [10]:
# # StoreDict In Database # db['store_dict']=storedict
In [11]:
# # Close Database # db.close()
In [12]:
# # Again, open database for reading data. # but at this time, open only for reading # data. and for read-only, use "r" # flag. # db=shelve.open(db_name,flag="r")
In [13]:
# # Read All Items (Key and Value both) # recover_data=db.items()
# # Again Open Database Because Now, # We Will See, usages of writeback option # db=shelve.open(db_name)
In [18]:
# # Print Stored List # printdb['store_list']
['Dog', 'cat', 'rat', 'snake', 'kite']
In [19]:
# # Append Value # db['store_list'].append("lion")
In [20]:
# # Check Appended Value # printdb['store_list']
['Dog', 'cat', 'rat', 'snake', 'kite']
In [21]:
# # As, You Can See, Value Is Not Updated, # Because Shelve Do not track small modification # By Default. Its Mean If You Want Modification, # Then, You Need to Modify Complete item. # # For Example : # # Take Data # modify=db['store_list'] # # Modify Data # modify.append("lion") # # Print Data # printmodify # # and modify entire item. # db['store_list']=modify # # Close database # db.close() # # But For This Problem # Their is A solution in shelve. # and that solution is writeback option. # for automatically detect changes in item, # you need to enable writeback options. # # Let's See Practical Example. # db=shelve.open(db_name,writeback=True) #
['Dog', 'cat', 'rat', 'snake', 'kite', 'lion']
In [22]:
# # Print List # printdb['store_list'] # # Append New Value # db['store_list'].append("Tiger") # # Again, Print List # printdb['store_list']