How to handle empty values in config files with ConfigParser?
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)
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')]
You need to set allow_no_value=True
optional argument when creating the parser object.