views:

120

answers:

4

How can I parse tags with no value on ini file with python configparser module?

For example, I have the below ini and I need to parse rb. On some ini the rb have integer value and on some hasn't at all like below. How can I do that with configparser without getting a valueerror? I use getint function

[section]
person=name
id=000
rb=
+3  A: 

You need to set allow_no_value=True optional argument when creating the parser object.

Santa
I tried to use config = ConfigParser.ConfigParser(allow_no_value=True) config.read(infFile)but i get this errorTypeError: __init__() got an unexpected keyword argument 'allow_no_value
AKM
Looks like that [argument](http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser) was only added in Python 2.7.
Santa
+1  A: 

Maybe use a try...except block:

    try:
        value=parser.getint(section,option)
    except ValueError:
        value=parser.get(section,option)

For example:

import ConfigParser

filename='config'
parser=ConfigParser.SafeConfigParser()
parser.read([filename])
print(parser.sections())
# ['section']
for section in parser.sections():
    print(parser.options(section))
    # ['id', 'rb', 'person']
    for option in parser.options(section):
        try:
            value=parser.getint(section,option)
        except ValueError:
            value=parser.get(section,option)
        print(option,value,type(value))
        # ('id', 0, <type 'int'>)
        # ('rb', '', <type 'str'>)
        # ('person', 'name', <type 'str'>) 
print(parser.items('section'))
# [('id', '000'), ('rb', ''), ('person', 'name')]
unutbu
A: 

Instead of using getint(), use get() to get the option as a string. Then convert to an int yourself:

rb = parser.get("section", "rb")
if rb:
    rb = int(rb)
Ned Batchelder
A: 

allow_no_value is only available in Py3k. Python 2.7 docs are wrong!

Use rb="".

leoluk