Press "Enter" to skip to content

How to Read Config File in Python?

Here is an example to read config file in Python using ConfigParser library.

The following example will read the below mentioned config.ini file:

[sepwin]
separateFrame=True
lookandfeel=Generic

[hms]
workingdirectory=f:\hospora
separateFrame=True
lookandfeel=Generic
width=1300
height=700
splashScreen=false
form=hospital.fmx
userid=hms/[email protected]

[debug]
serverURL=/forms/lservlet/debug

[webutil]
WebUtilArchive=frmwebutil.jar,jacob.jar
WebUtilLogging=off
WebUtilLoggingDetail=normal
WebUtilErrorMode=Alert
WebUtilDispatchMonitorInterval=5

Python Program to Read Config File Using ConfigParser Library

In the below Python program, it will read the above mentioned config.ini file. First, it will describe all the sections of the config file, and then it will read the configuration value for form under [hms] section, splashScreen value under [hms] section and WebUtilDispatchMonitorInterval value under [webutil] section.

from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('config.ini')
print('Sections in the file:', cfg.sections())
print('hms: form value: ', cfg.get('hms','form'))
print('hms: splashScreen value: ', cfg.getboolean('hms','splashScreen'))
print('webutil: WebUtilDispatchMonitorInterval value: ', cfg.getint('webutil','WebUtilDispatchMonitorInterval'))

Output:

Sections in the file: ['sepwin', 'hms', 'debug', 'webutil']
hms: form value:  hospital.fmx
hms: splashScreen value:  False
webutil: WebUtilDispatchMonitorInterval value:  5

Process finished with exit code 0

See also: