Python Shelve Module

The shelve module allows you to save a class or a structured object to an external file, separate from your program.

Why use it? Once you've created the object, you can reload it at any time, whether in the same program or in different ones.

    A Practical Example

    To show how the shelve module works, let's go through a practical example.

    We'll create two separate programs (A and B).

    1. Program A saves a structured object.
    2. Program B reads the object.

    how to transfer class data using Python's shelve module

    How to Create and Save an Object

    Program A creates a class called Rubrica and adds an object to it.

    1. import shelve
    2. db = shelve.open('nome')
    3. class Rubrica:
    4. def __init__(self, nome):
    5. self.nome = nome
    6. var = Rubrica('Minini')
    7. db['Andrea'] = var
    8. db.close()

    The class and its data are saved to an external file (nomefile) using the shelve module.

    How to Read the Object

    Program B then reads the object (nomefile) and retrieves the data stored in it.

    1. import shelve
    2. class Rubrica:
    3. def __init__(self, nome):
    4. self.nome = nome
    5. db = shelve.open('db')
    6. var = db['Andrea']
    7. print(var.nome)

    The output of the program is:

    Minini

    With this module, you can easily transfer a class and its data from one program to another using a binary file.

    And that’s it!

     

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Python Modules