Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...