Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle empty values in config files with ConfigParser?

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

For example, I have the following ini and I need to parse rb. In some ini files rb has integer values and on some no value at all like the example below. How can I do that with configparser without getting a valueerror? I use the getint function

[section]
person=name
id=000
rb=
like image 671
AKM Avatar asked Aug 27 '10 18:08

AKM


People also ask

What is ConfigParser ConfigParser ()?

ConfigParser is a Python class which implements a basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows to write Python programs which can be customized by end users easily.

How do I read a .ini file?

How to Open and Edit INI Files. It's not a common practice for people to open or edit INI files, but they can be opened and changed with any text editor. Just double-clicking it will automatically open it in the Notepad application in Windows.

What is config () in Python?

A Python configuration file is a pure Python file that populates a configuration object. This configuration object is a Config instance.


2 Answers

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

like image 76
Santa Avatar answered Sep 17 '22 15:09

Santa


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')]
like image 26
unutbu Avatar answered Sep 19 '22 15:09

unutbu