views:

55

answers:

2

I would like store some configuration data in a config file. Here's a sample section:

[URLs]
Google, www.google.com
Hotmail, www.hotmail.com
Yahoo, www.yahoo.com

Is it possible to read this into a list of tuples using the ConfigParser module? If not, what do I use?

A: 
import ConfigParser

config = ConfigParser.ConfigParser()
config.add_section('URLs')
config.set('URLs', 'Google', 'www.google.com')
config.set('URLs', 'Yahoo', 'www.yahoo.com')

with open('example.cfg', 'wb') as configfile:
    config.write(configfile)

config.read('example.cfg')
config.items('URLs')
# [('google', 'www.google.com'), ('yahoo', 'www.yahoo.com')]

The documentation mentions:

The ConfigParser module has been renamed to configparser in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

Adam Bernier
+4  A: 

Can you change the separator from comma (,) to a semicolon (:) or use the equals (=) sign? In that case ConfigParser will automatically do it for you.

For e.g. I parsed your sample data after changing the comma to equals:

# urls.cfg
[URLs]
Google=www.google.com
Hotmail=www.hotmail.com
Yahoo=www.yahoo.com

# Scriptlet
import ConfigParser
filepath = '/home/me/urls.cfg'

config = ConfigParser.ConfigParser()
config.read(filepath)

print config.items('URLs') # Returns a list of tuples.
# [('hotmail', 'www.hotmail.com'), ('google', 'www.google.com'), ('yahoo', 'www.yahoo.com')]
Manoj Govindan