[Tutor] [Q] ConfigParser

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 16 Jan 2002 13:48:23 -0800 (PST)


On Wed, 16 Jan 2002, Young-Jin Lee wrote:

> I have a problem using ConfigParser module. I created a config file in
> the working directory and tried to read it, but the following scripts
> gave me nothing.
> 
> import ConfigParser
> cfg = ConfigParser.ConfigParser()
> cfg.read( 'test.cfg' )    # It returned None.
> 
> Why can't ConfigParser module read the config file in the same
> directory?


ConfigParser's read() method is supposed to return None --- it's a
"side-effect" function that doesn't have a useful return value.  After
calling read(), try using the get() method, and you should see useful
values.  Here's a small example that might help:


###
from ConfigParser import ConfigParser, NoSectionError
from StringIO import StringIO

sample_input = StringIO("""
[General]
name=Young Jin
email=ylee12
""")


config = ConfigParser()
config.readfp(sample_input)
print config.get("General", "name")
print config.get("General", "email")

try:
    print config.get("general", "email")
except NoSectionError:
    print "Notice that ConfigParser is case-sensitive."
###



Let's run this program and see what happens:

###
[dyoo@tesuque dyoo]$ python configparser.py
Young Jin
ylee12
Notice that ConfigParser is case-sensitive.
###


Hope this helps!