6

I'm working on reading an external config file in Python(3.7) using the module configparser.

Here is my sample configuration file config.ini

[ABC]
ch0 = "C:/Users/utility/ABC-ch0.txt"
ch1 = "C:/Users/utility/ABC-ch1.txt"

[settings]
script = "C:/Users/OneDrive/utility/xxxx.exe"
settings = "C:/Users/OneDrive/xxxxxxConfig.xml"

Here is the sample code I tried:

import configparser
config = configparser.ConfigParser()

config.read('config.ini')
ch0 = config.get('ABC','ch0')
print(ch0)

And here is the error code I am getting, not sure what I am doing wrong:

NoSectionError: No section: 'ABC'

Any help is much appreciated. Thanks in advance.

Anil
  • 2,539
  • 6
  • 33
  • 42
Pbch
  • 179
  • 2
  • 4
  • 12
  • Print out the the return value of `config.read('config.ini')` and post the result. – Klaus D. Apr 29 '19 at 07:41
  • Code works for me perfectly fine with the sample ini you provided for `python 3.7` for me – Devesh Kumar Singh Apr 29 '19 at 07:47
  • 1
    I would suspect that, as you give a relative path for the config file you are not reading the expected one. You should add a debug print with `print(os.getcwd())` – Serge Ballesta Apr 29 '19 at 07:47
  • Is your python file and the config.ini in the same path? if not, place your config.ini in the path of your python file. and then run the script. it should work – Nithin Apr 29 '19 at 07:48
  • Yes, for e.g if I provide the wrong path, e.g. config.read('/xyz/config.ini'), I do get the error configparser.NoSectionError: No section: 'ABC', so provide the correct path to config.ini and you should be fine! I tried that in my answer below and it works! Check it out! @pbch – Devesh Kumar Singh Apr 29 '19 at 08:51

2 Answers2

8

Your code is absolutely fine.

This line:

config.read('config.ini')

tries to read the file from the same directory as the .py file you're running. So you have 3 options:

  1. move the config.ini file to be next to the .py file
  2. use a correct relative path when reading the file
  3. use an absolute path when reading the file (not recommended for portability reasons)
ruohola
  • 21,987
  • 6
  • 62
  • 97
3

Looks like the issue is not finding config.ini in the correct location, you can avoid that by doing os.getcwd.

import configparser
import os
config = configparser.ConfigParser()

#Get the absolute path of ini file by doing os.getcwd() and joining it to config.ini
ini_path = os.path.join(os.getcwd(),'config.ini')
config.read(ini_path)
ch0 = config.get('ABC','ch0')
print(ch0)
#"C:/Users/utility/ABC-ch0.txt"
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40