Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigParser.MissingSectionHeaderError: File contains no section headers

Tags:

configparser

I am trying to fetch data from a .cfg (configuration file) in python but I am always getting the error

ConfigParser.MissingSectionHeaderError: File contains no section headers.

The screenshot of the problem

Here is the link for the .cfg file:

http://www.mediafire.com/file/66k9m7trxo7krx9/a.cfg/file

like image 658
joginder singh Avatar asked Oct 16 '25 10:10

joginder singh


2 Answers

Most probably you have parameters without section, e.g.:

name1 = value1
name2 = value2

According documentation there should be a section.

I may suggest the following solutions:

Add section explicitly

Add section in ini file, e.g:

[default]
name1 = value1
name2 = value2

Add section implicitly

from configparser import ConfigParser

parser = ConfigParser()
with open('config.ini') as stream:
    parser.read_string('[default]\n' + stream.read())

# now you can use it for parameters without section
print(parser.get('default', 'name1'))
like image 96
Maxim Suslov Avatar answered Oct 19 '25 11:10

Maxim Suslov


The ConfigParser module assumes that config files have section headers. Section headers are used to keep configurations of one type together. Write [Default] in the first line of your configuration file. This will tell ConfigParser that there is only one header and that is the default.

like image 41
Abhishek Kumar Avatar answered Oct 19 '25 13:10

Abhishek Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!