Parsing a conf file

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Mar 5 15:41:09 EST 2003


>>>>> "Simon" == Simon Faulkner <news at titanic.co.uk> writes:

    Simon> Hello All, Is there a simple / recommended way of parsing a
    Simon> setting from a conf file?


    Simon> server = Stafford

It depends somewhat on the format of the whole file, but for a first
pass

conf = {}
for line in file('test.conf'):
   vals = line.split('=')
   if len(vals)!=2: continue
   key, val = vals
   conf[key.strip()] = val.strip()

print 'Server is', conf['server']

Now some comments

conf = {}    #conf is a dictionary mapping keys to values
for line in file('test.conf'):
   vals = line.split('=')     #split the lines at the equal token
   if len(vals)!=2: continue  #a valid split has two entries
   key, val = vals            # the key and the value
   conf[key.strip()] = val.strip()   #enter the result to tin the
                                     #dictionary, removing whitespace

# show that it worked
print 'Server is', conf['server']


You'll need a recent version of python to split on an arbitrary token.

John Hunter





More information about the Python-list mailing list