Python: How to create a dictionary from properties file while omitting comments

Given a properties file test.txt as you've described:

foo=bar
#skip me
bar=baz
baz=foo
#skip me too!

You can do the following:

>>> D = dict( l.rstrip().split('=') for l in open("test.txt")
              if not l.startswith("#") )
>>> D
{'baz': 'foo', 'foo': 'bar', 'bar': 'baz'}

This seems just like the code you said you tried using if not line.startswith('#'), so hopefully this working example will help you pinpoint the bug.


You should just use the built-in configparser which is made to read ini-style configuration files. It allows comments using ; and # by default, so it should work for you.

For .properties files you might need to trick a bit as the configparser generally expects section names. You can do this easily by adding a dummy section while reading it though:

>>> from configparser import ConfigParser
>>> config = ConfigParser()
>>> with open(r'C:\Users\poke\Desktop\test.properties') as f:
        config.read_string('[config]\n' + f.read())

>>> for k, v in config['config'].items():
        print(k, v)

foo bar
bar baz
baz foo

(Using the same example file as mtitan8)

For Python 2, use from ConfigParser import ConfigParser instead.


To address your newest constraint about blank lines, I would try something like:

myprops = {}
with open('filename.properties', 'r') as f:
    for line in f:
        line = line.rstrip() #removes trailing whitespace and '\n' chars

        if "=" not in line: continue #skips blanks and comments w/o =
        if line.startswith("#"): continue #skips comments which contain =

        k, v = line.split("=", 1)
        myprops[k] = v

It's very clear and it's easy to add on extra constraints, whereas using a dict comprehension will get quite bloated. However, you could always format it nicely

myprops = dict(line.strip().split('=') 
               for line in open('/Path/filename.properties'))
               if ("=" in line and 
                   not line.startswith("#") and
                   <extra constraint> and
                   <another extra constraint>))