User Tools

Site Tools


programming-languages:python:shelve

Shelve

The shelve module allows to save, on an external file, any kind of Python's object. This file is created as a Python dictionary where the values are the objects to be saved.

It's worth to notice that to add elements to a given key, it's necessary to work on a copy of key itself.

shelve.py
#!/usr/bin/env python3
 
import shelve
 
 
class Stock(object):
    def __init__(self):
        self.a = "key_a"
        self.b = "key_b"
        self.c = "key_c"
 
    def save(self, filename, key, value):
        """
        Save in databese.
        """
        db = shelve.open(filename)  # open (<filename> is created)
        db[key] = value  # save (<value> is any Python object)
        db.close()  # close
 
    def add(self, filename, key, value):
        """
        Add a value to a given key.
        """
        db = shelve.open(filename)
        copy_key = db[key]  # work on a copy
        copy_key.append(value)
        db[key] = copy_key
        db.close()
 
    def cancel(self, filename, key):
        """
        Delete a given key.
        """
        db = shelve.open(filename)
        del db[key]
        db.close()
 
    def get_all(self, filename):
        """
        Return a list with all keys and values.
        """
        db = shelve.open(filename)
        keys = list(db.keys())
        values = list(db.values())
        db.close()
        return keys, values
 
    def main(self):
        self.save("file", self.a, [])
        self.save("file", self.b, [])
 
        self.add("file", self.a, 1)
        self.add("file", self.b, 2)
 
        k, v = self.get_all("file")
        for i in range(len(k)):
            print(k[i], ": ", v[i])
 
        self.cancel("file", self.b)
 
        self.save("file", self.c, [2])
 
        k, v = self.get_all("file")
        for i in range(len(k)):
            print(k[i], ": ", v[i])
 
 
if __name__ == '__main__':
    stock = Stock()
    stock.main()
programming-languages/python/shelve.txt · Last modified: 2020/04/03 09:36 (external edit)