Saving Variables

Variables can be saved or made to persist after the program has closed with the shelve module.

i>>> import shelve
i>>> shelfFile = shelve.open('mydata')
i>>> cats = ['Zophie', 'Pooka', 'Simon']
i>>> shelfFile['cats'] = cats
i>>> shelfFile.close()
i>>> shelfFile = shelve.open('mydata')
i>>> type(shelfFile)
<class 'shelve.DbfilenameShelf'>
i>>> shelfFile['cats']
['Zophie', 'Pooka', 'Simon']
i>>> shelfFile.close()

Shelf files are like dictionaries and use keys() and values() to return keys and values.

i>>> shelfFile = shelve.open('mydata')
i>>> list(shelfFile.keys())
['cats']
i>>> list(shelfFile.values())
[['Zophie', 'Pooka', 'Simon']]
i>>> shelfFile.close()