|
| 1 | +--- |
| 2 | +title: Python Shelve Module - Python Cheatsheet |
| 3 | +description: A “shelf” is a persistent, dictionary-like object. in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. |
| 4 | +--- |
| 5 | + |
| 6 | +# Python Shelve Module |
| 7 | + |
| 8 | +<base-disclaimer> |
| 9 | + <base-disclaimer-title> |
| 10 | + From the <a target="_blank" href="https://docs.python.org/3/library/shelve.html">Python 3 documentation</a> |
| 11 | + </base-disclaimer-title> |
| 12 | + <base-disclaimer-content> |
| 13 | + A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings. |
| 14 | + </base-disclaimer-content> |
| 15 | +</base-disclaimer> |
| 16 | + |
| 17 | +## Save variables |
| 18 | + |
| 19 | +```python |
| 20 | +>>> import shelve |
| 21 | + |
| 22 | +>>> wife = ['Pretty', 'Lovely', 'Nice'] |
| 23 | +>>> with shelve.open('mydata') as shelf_file: |
| 24 | +... shelf_file['wife'] = wife |
| 25 | +``` |
| 26 | + |
| 27 | +## Open and read variables: |
| 28 | + |
| 29 | +```python |
| 30 | +>>> with shelve.open('mydata') as shelf_file: |
| 31 | +... print(type(shelf_file)) |
| 32 | +... print(shelf_file['wife']) |
| 33 | +... |
| 34 | +# <class 'shelve.DbfilenameShelf'> |
| 35 | +# ['Pretty', 'Lovely', 'Nice'] |
| 36 | +``` |
| 37 | + |
| 38 | +Just like dictionaries, `shelf` values have `keys()` and `values()` methods that will return list-like values of the keys and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them to the `list()` function to get them in list form. |
| 39 | + |
| 40 | +```python |
| 41 | +>>> with shelve.open('mydata') as shelf_file: |
| 42 | +... print(list(shelf_file.keys())) |
| 43 | +... print(list(shelf_file.values())) |
| 44 | +... |
| 45 | +# ['wife'] |
| 46 | +# [['Pretty', 'Lovely', 'Nice']] |
| 47 | +``` |
0 commit comments