How to read a config file with Python's configparser?
Question:
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.
Answers:
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"
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:
- move the config.ini file to be next to the .py file
- use a correct relative path when reading the file
- use an absolute path when reading the file (not recommended for portability reasons)
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.
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"
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:
- move the config.ini file to be next to the .py file
- use a correct relative path when reading the file
- use an absolute path when reading the file (not recommended for portability reasons)