Using the Python shelve module, you can store the data to be saved in binary files in the shelf file. Another program can read the shelf file and use it for business logic. That is, the Shelve module can persist data, but in binary form.

Write data:

import shelve

' ''Read and write variables using shelve'' '

Write to the data file
shelf_file = shelve.open('book_data')
books = ['the authority'.'The twelve Rules of Life'.'A game a pastime']
shelf_file['books'] = books
shelf_file.close()
Copy the code

Read data:

shelf_file = shelve.open('book_data')
print(list(shelf_file.keys()))
print(list(shelf_file.values()))
shelf_file.close()
Copy the code

Running results:

[‘ Books ‘] [[‘ Travel ‘, ‘Twelve Rules of Life ‘,’ One Game at a time ‘]]

Values of the shelf type have keys() and values() methods, which return keys or values that are like lists in shelf, respectively. Since they are only similar, they should be passed to the list() function to return the actual list.

The shelve module creates three new persistence files in the execution directory:


If you want to save data in Python programs, the Shelve module is handy