This is an easy-to-learn module that allows for the storage of all types. It functions similar to a dictionary, although it only allows keys to be strings. To store values, first import shelve, then use it just like a dictionary:
import shelve """this will create a database if you don’t already have one and open it if you do""" myshelf = shelve.open('mydatabase') myshelf['key1'] = 4 # remember, while the key must be a string, the value can be any type print(myshelf['key1']) #will give me 4 myshelf.close()
View code on GitHub.
You may have noticed that we closed the dictionary. If you forget to write that, the data will not save, so it’s best to remember.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact email@example.com for inquiries.