New here? Register and read our Community Rules. Accounts are approved by hand.

Parse simple config files in Python

MicrolinuxMicrolinux Member
edited February 2013 in Tutorials

I was looking for a clean way to parse simple config files in Python, i.e. var = val, and came up with this. It parses variables into a namedtuple.

Maybe someone else will find it useful.

from collections import namedtuple

def get_config(file, sep="="):
  fh = open(file, "r")
  vars = []
  vals = []

  for line in fh:
    line = line.split(sep)
    vars.append(line[0].strip())
    vals.append(line[1].strip())

  fh.close()

  return namedtuple("ConfigTuple", vars)._make(vals)

Comments

Sign In or Register to comment.