Parsing a conf file

Steven Taschuk staschuk at telusplanet.net
Wed Mar 5 22:47:10 CET 2003


Quoth Simon Faulkner:
  [...]
> For eample, I have a file /etc/program.conf which might have a setting
> like
> 
> >>
> #My conf file
> 
> 
> server = Stafford
> <<
> 
> How do I parse out the name Stafford for the key server??

In this particular case, it's probably as simple as
	settings = {}
	for line in open('/etc/program.conf'):
		line = line.lstrip()
		if not line or line.startswith('#'):
			continue
		if '=' not in line:
			print 'grr... line without = in conf file'
		else:
			key = line[:line.index('=')].rstrip()
			value = line[line.index('=')+1:]
			settings[key] = value
(Untested.)

For a more sophisticated syntax, see the ConfigParser module in
the standard library.  And if you don't mind the security
problems, the built-in execfile() is handy.

-- 
Steven Taschuk                Aral: "Confusion to the enemy, boy."
staschuk at telusplanet.net      Mark: "Turn-about is fair play, sir."
                              (_Mirror Dance_, Lois McMaster Bujold)





More information about the Python-list mailing list