0

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Kiki
  • 67
  • 10
  • 1
    I think this is explained in the [documentation of ConfigParser](https://docs.python.org/3/library/configparser.html)? – user202729 Sep 21 '20 at 13:55
  • Possible duplicate of [python - What is the intended use of the DEFAULT section in config files used by ConfigParser? - Stack Overflow](https://stackoverflow.com/questions/124692/what-is-the-intended-use-of-the-default-section-in-config-files-used-by-configpa) – user202729 Sep 21 '20 at 14:04
  • @user202729 yeah, checked on that link before. It showed windows.ini file. But mine is text file. Not sure if it correlates. – Kiki Sep 21 '20 at 14:07
  • 1
    @Kiki I think you should state more clearly the fact that the default section is not actually in your file... – Tomerikoo Sep 21 '20 at 14:09

1 Answers1

1

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
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214