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=
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 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.
A Python configuration file is a pure Python file that populates a configuration object. This configuration object is a Config instance.
You need to set allow_no_value=True
optional argument when creating the parser object.
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With