32

Using ConfigParser's has_section() method I can check if a section exists in a file, such as:

config.has_section(section_name) 

What would be a command to check if a key exists as well? So it would be possible to verify that both a section and key exists before querying the value using:

value = config.get(section, key)

Thanks in advance!

sk8forether
  • 247
  • 2
  • 9
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • this might help you out http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section – samrap Jan 11 '14 at 02:07

1 Answers1

50

In addition to has_section, there is also a has_option method:

config.has_option(section, option)

From the Python documentation:

has_option*(section, option)*
If the given section exists, and contains the given option, return True; otherwise return False. If the specified section is None or an empty string, DEFAULT is assumed.

John1024
  • 109,961
  • 14
  • 137
  • 171