Search code examples
pythondefaultconfigparser

"DEFAULT" section with no values in config text file


Why there is a section named "DEFAULT" but with no values in my config text file?

I have a text file "policy.txt" with my configurations in it. So I was running a simple configparser code in Python which looks like this:

>>> from configparser import ConfigParser
>>> config = ConfigParser()
>>> config.read('policy.txt')
['policy.txt']
>>> for key in config:
...     print(key)
...

The numbers you see (1 to 5) are the section names in my policy.txt file. This is the result:

DEFAULT
1
2
3
4
5

So I was wondering what is stored in "DEFAULT" section. Then I ran this code segment:

>>> for key in config['DEFAULT']:
...     print(key)
...
...
>>>

But it seems like the section isn't storing anything. So why is it there in my policy.txt file?

Any helpful idea is appreciated.


Solution

  • DEFAULT is a “special” section that is always present in a ConfigParser instance. It stores fallback values that are used as defaults when a value in another section is missing.

    If you want to iterate over the sections in your configuration and want to exclude the default, use sections():

    >>> for key in config.sections():
    ...     print(key)
    
    1
    2
    3
    4
    5