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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.