How to handle empty values ​​in configuration files using ConfigParser?

How can I parse tags without a value in an ini file using the python configparser module?

For example, I have the following ini, and I need to parse rb. In some ini files, rb has integer values, but for some value it doesn't exist at all, as in the example below. How can I do this using configparser without getting an error value? I am using the getint function

[section] person=name id=000 rb= 
+6
python configparser
source share
4 answers

Perhaps 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')] 
+6
source share

When creating a parser object, you must set the optional argument allow_no_value=True .

+11
source share

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

 rb = parser.get("section", "rb") if rb: rb = int(rb) 
+3
source share

Since the python 2.6 question is still unanswered, the following will work with python 2.7 or 2.6. This replaces the internal regular expression used to parse the option, delimiter, and value in ConfigParser.

 def rawConfigParserAllowNoValue(config): '''This is a hack to support python 2.6. ConfigParser provides the option allow_no_value=True to do this, but python 2.6 doesn't have it. ''' OPTCRE_NV = re.compile( r'(?P<option>[^:=\s][^:=]*)' # match "option" that doesn't start with white space r'\s*' # match optional white space r'(?P<vi>(?:[:=]|\s*(?=$)))\s*' # match separator ("vi") (or white space if followed by end of string) r'(?P<value>.*)$' # match possibly empty "value" and end of string ) config.OPTCRE = OPTCRE_NV config._optcre = OPTCRE_NV return config 

Use as

  fp = open("myFile.conf") config = ConfigParser.RawConfigParser() config = rawConfigParserAllowNoValue(config) 

Side note

ConfigParser for Python 2.7 has OPTCRE_NV, but if we used it in the above function, the regular expression will return None for vi and value, which will cause ConfigParser to crash. Using the function above returns an empty string for vi and a value, and everyone is happy.

0
source share

All Articles