Search code examples
pythonxmlperlconfigparser

Is something like ConfigParser appropriate for saving state (key, value) between runs?


I want to save a set of key, value pairs (string, int) between runs of a Python program, reload them on subsequent runs and write the changes to be available on the next run.

I don't think of this data as a configuration file, but it would fit the ConfigParser capabilities quite well. I would only need two [sections]. It's only a few hundred pairs and very simple so I don't think it's necessary to do an actual database.

Is it appropriate to use ConfigParser in this way? I've also considered using Perl and XML::Simple. What about that? Is there a way to do this in bash without Python or Perl?


Solution

  • Well, you have better options. You can for example use pickle or json format. Pickle serializing module is very easy to use.

    import cPickle
    cPickle.dump(obj, open('save.p', 'wb')) 
    obj = cPickle.load(open('save.p', 'rb'))
    

    The format is not human readable and unpickling is not secure against erroneous or maliciously constructed data. You should not unpickle untrusted data.

    If you are using python 2.6 there is a builtin module called json. It is as easy as pickle to use:

    import json
    encoded = json.dumps(obj)
    obj = json.loads(encoded)
    

    Json format is human readable and is very similar to the dictionary string representation in python. And doesn't have any security issues like pickle.

    If you are using an earlier version of python you can simplejson instead.