Config parser opening file but not returning anything?

1k Views Asked by At

I am trying to use config parser like I normally do but for some reason I am not pulling any of the sections?

My Code:

import os, configparser

## Get directory path
dir_path = os.path.dirname(os.path.realpath(__file__))
file_path = dir_path + "\\development.ini"

## Setup config parser object
config = configparser.ConfigParser()

## Read file into config parser
with open(file_path) as file:
    config.read_file(file)

print(config.sections())

My Config File:

[MYSQL]
Host = 192.168.1.11
Port = 3306
Username = server
Password = (Removed)
Database = server

Code Output:

[]

No errors and just an empty list is returned on "config.sections()"? I am confused and I am sure it is something quite simple I am missing... Any help would be appreciated.

2

There are 2 best solutions below

6
On BEST ANSWER

This is because you only have the default section. According to the doc :

Return a list of the sections available; the default section is not included in the list. https://docs.python.org/3/library/configparser.html

Then, you don't have to open the file. The config parser will do it for you.

## Setup config parser object
config = configparser.ConfigParser()

## Read file into config parser
config.read(file)

print(config.sections())

Here's an example :

config.ini :

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

test.py :

import configparser
config = configparser.ConfigParser()
config.read('config.ini')
print(config.sections())

Output:

['bitbucket.org', 'topsecret.server.com']
1
On

I guess the issue is in accessing the file only. I tried with below code with both files in one folder, runs fine. Try changing to .cfg

from configparser import ConfigParser

config = ConfigParser()
config.read("dev.cfg")

print(config.sections())

or your code

import os, configparser

## Get directory path
dir_path = os.path.dirname(os.path.realpath(__file__))
file_path = dir_path + "\\dev.cfg"

## Setup config parser object
config = configparser.ConfigParser()

## Read file into config parser
with open(file_path) as file:
    config.read_file(file)

print(config.sections())