Search code examples
pythonconfigparser

Python: ConfigParser.NoSectionError: No section: 'TestInformation'


I am getting ConfigParser.NoSectionError: No section: 'TestInformation' error using the above code.

def LoadTestInformation(self):        
    config = ConfigParser.ConfigParser()    
    print(os.path.join(os.getcwd(),'App.cfg'))

    with open(os.path.join(os.getcwd(),'App.cfg'),'r') as configfile:       
        config.read(configfile)
        return config.items('TestInformation')

The file path is correct, I have double checked. and the config file has TestInformation section

[TestInformation]

IEPath = 'C:\Program Files\Internet Explorer\iexplore.exe'

URL = 'www.google.com.au'

'''date format should be '<Day> <Full Month> <Full Year>'

SystemDate = '30 April 2013'

in a app.cfg file. Not sure what I am doing wrong


Solution

  • Use the readfp() function rather than read() since you are opening the file before reading it. See Official Documentation.

    def LoadTestInformation(self):        
        config = ConfigParser.ConfigParser()    
        print(os.path.join(os.getcwd(),'App.cfg'))
    
        with open(os.path.join(os.getcwd(),'App.cfg'),'r') as configfile:       
            config.readfp(configfile)
            return config.items('TestInformation')
    

    You can continue to use read() if you skip the file opening step and instead the full path of the file to the read() function

    def LoadTestInformation(self):        
        config = ConfigParser.ConfigParser()    
        my_file = (os.path.join(os.getcwd(),'App.cfg'))
        config.read(my_file)
        return config.items('TestInformation')