save a dictionary in a file

Mariano Draghi mdraghi at prosud.com
Mon Nov 15 13:44:37 EST 2004


Luis P. Mendes wrote:
> Hash: SHA1
> 
> Hi,
> 
> my program builds a dictionary that I would like to save in a file.
> 
> My question is what are the simple ways to do it?

We implemented this for SiGeFi (sf.net/projects/sigefi/)

 From config.py

class PersistentDict(dict):
     '''Persistent dictionary.

     It's a dictionary that saves and loads its data to a file.
     '''

     def __init__(self, nomarchivo):
         '''Creates a PersistentDict instance.

         Receives a filename, but if the file does not exist (yet) 
starts to work
         with an empty data set and will create the file when the data 
is saved.

         :Parameters:
             - `nomarchivo`: file where the data is saved.
         '''
         self._nomarchivo = nomarchivo
         dict.__init__(self)

         if not os.access(nomarchivo, os.W_OK):
             return

         arch = open(nomarchivo, 'r')
         olddict = cPickle.load(arch)
         arch.close()
         self.update(olddict)
         return

     def save(self):
         '''Saves the data to disk.'''
         arch = open(self._nomarchivo, 'w')
         cPickle.dump(self, arch)
         arch.close()
         return



Regards,

-- 
Mariano




More information about the Python-list mailing list