Using the shelve module as a database
Files offer us persistent storage. The simple use of files is limited by the fact that the data must be accessed sequentially. How can we access items in an arbitrary order?
We'll use the term "database" for a file (a set of files) on which we're going to perform Create, Retrieve, Update, and Delete (CRUD) operations on data elements in an arbitrary order. If we create objects of a consistent size, we can open an ordinary text file in r+
mode and use the seek()
method to position at the start of any particular record. This is rather complex, however, and we can do better.
The core database concept of readable and writable storage can be extended with a seemingly endless list of ancillary features. We'll ignore locking, logging, auditing, journaling, distributed transaction management, and many other features, for now to focus on the core feature of persistence.
The shelve
module provides us with a very flexible database. A shelf object behaves like an ordinary...