Parsing config file with python

Today I was reading python code parsing a configuration file, an easy one with key = value and comment starting with #, I did not like the code so I wrote something just for fun:

config_file = ...
config = {}
with open(config_file, 'r') as f:
    config = dict((k.strip(), v.strip().split('#', 1)[0].strip())
                  for k, v in
                  (l.split('=') for l in
                   (line.strip() for line in
                    f) if (l and not l.startswith('#'))))

This code reads a configuration file into a dictionary so that you can get access configuration values easily in your code.

2 thoughts on “Parsing config file with python

  1. strange, doesn’t python have a proper configuration library class?

    In groovy reading a config file is as easy as writing:

    def config = new ConfigSlurper().parse(new File(config_file).toURL())

    the ConfigSlurper class, moreover, provides a more structured and complex format (if needed) without any other effort.

    1. Yes Federico, python has way to parse INI files, this is just a stupid hack I wrote to highlight that using standard libs produce more readable code.

Leave a Reply

Your email address will not be published. Required fields are marked *