Using Python to parse config files
Alot of tools out there have some sort of configuration which, at run time, is read and used in the process accordingly. When writing tools, my config file format has always been something like:
title: My Tool
# commented out line
description: This is my tool. # another comment
Since I’m using Python for much of my scripting these days, I decided to write a small parser to handle this type of config. So here’s what I’ve come up with:
import fileinput, re def parse(file=None, delim=':'): ''' Parses a config file formatted like: foo: bar # comments: out line - comments allowed (#) - empty lines allowed - spaces allowed ''' d = {} if file is None: return -1 for line in fileinput.input(file): if not line.strip(): # skip empty or space padded lines continue if re.compile('^#').search(line) is not None: # skip commented lines continue else: # pick up key and value pairs kvp = line.strip().split(delim) if kvp[1].strip().split('#') is not None: d[kvp[0].strip()] = kvp[1].split('#')[0].strip() else: d[kvp[0].strip()] = kvp[1].strip() return d
Seems to work well so far. I wonder if there’s a config file standard out there?
Paul said,
Wrote on April 13, 2009 @ 12:40:18
try out the ConfigParser module that comes with the core python install for reading and writing standard config files.
Posted from United StatesK-Meleon 1.5.1 Windows XP