Python - How to read config.ini files - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to see how to read python config .ini file.
The python’s configparser module used to read the .ini files, typically these file contains configuration information.
The following few examples illustrate some of the more interesting features of the ConfigParsermodule. First, consider a sample .ini file:
[dev]
LOG_FILE_PATH = %(BASEDIR)s/app.log
secret_key = DEV_SECRET_KEY
secret_value = DEV_SECRET_VALUE
BASEDIR = /opt/logs
port = 8080
is_debug = on
app_base_url = dev.myapp.com

[stage]
LOG_FILE_PATH = %(basedir)s/app.log
secret_key = STAGE_SECRET_KEY
secret_value = STAGE_SECRET_VALUE
BASEDIR = /opt/logs
port = 8088
is_debug = off
app_base_url = stage.myapp.com
Let’s read the above app_config.ini file using the python configparser module.
from configparser import ConfigParser

cfg = ConfigParser()
cfg.read('app_config.ini')

print ("Sections : ", cfg.sections())

for section in cfg.sections():
    print("SECTION -> ",section)
    print("-------------------")
    print('LOG_FILE_PATH - ' , cfg.get(section,'LOG_FILE_PATH'))
    print('SECRET_KEY - ', cfg.get(section,'SECRET_KEY'))
    print('SECRET_VALUE - ' , cfg.get(section,'SECRET_VALUE'))
    print('PORT - ' , cfg.get(section,'PORT'))
    print('APP_BASE_URL - ' , cfg.get(section,'APP_BASE_URL'))
    print('IS_DEBUG - ', cfg.getboolean(section, 'IS_DEBUG'))
Output:
Sections :  ['dev', 'stage']
SECTION ->  dev
-------------------
LOG_FILE_PATH -  /opt/logs/app.log
SECRET_KEY -  DEV_SECRET_KEY
SECRET_VALUE -  DEV_SECRET_VALUE
PORT -  8080
APP_BASE_URL -  dev.myapp.com
IS_DEBUG - True
SECTION ->  stage
-------------------
LOG_FILE_PATH -  /opt/logs/app.log
SECRET_KEY -  STAGE_SECRET_KEY
SECRET_VALUE -  STAGE_SECRET_VALUE
PORT -  8088
APP_BASE_URL -  stage.myapp.com
IS_DEBUG - False
Configuration parameters are case insensitive. Thus, if your program is reading a parameter 'log_file_path', it does not matter if the configuration file uses 'log_file_path', 'LOG_FILE_PATH', or 'Log_File_Path
Configuration parameters can include variable substitutions such as '%(BASEDIR)s' as seen in the file. These substitutions are also case insensitive.
The definition order of configuration parameters does not matter in these substitutions. For example, in config.ini, the LOGFILE parameter makes a reference to the BASEDIR parameter, which is defined later in the file.
The values in configuration files are often interpreted correctly even if they don’t exactly match Python syntax or datatypes. For example, the 'on' value of the IS_DEBUG parameter is interpreted as True by the cfg.getboolean()method.
The configuration files have the ability to merge together, suppose we have separate .ini file for each environment, we can merge among them and read the content.
[prod]
LOG_FILE_PATH = %(BASEDIR)s/app.log
secret_key = PROD_SECRET_KEY
secret_value = PROD_SECRET_VALUE
BASEDIR = /opt/app/logs
port = 8000
is_debug = off
app_base_url = myapp.com

read the prod_app_config.ini file soon after reading the config.ini file like below, so that both the config files made available to read the content.
from configparser import ConfigParser

cfg = ConfigParser()
cfg.read('app_config.ini')
cfg.read('prod_app_config.ini')

print ("Sections : ", cfg.sections())

for section in cfg.sections():
    print("SECTION -> ",section)
    print("-------------------")
    print('LOG_FILE_PATH - ' , cfg.get(section,'LOG_FILE_PATH'))
    print('SECRET_KEY - ', cfg.get(section,'SECRET_KEY'))
    print('SECRET_VALUE - ' , cfg.get(section,'SECRET_VALUE'))
    print('PORT - ' , cfg.get(section,'PORT'))
    print('APP_BASE_URL - ' , cfg.get(section,'APP_BASE_URL'))
    print('IS_DEBUG - ' , cfg.getboolean(section,'is_debug'))

you can observe the Sections in the output now we could see [‘dev’, ‘stage’, ‘prod’].
Sections :  ['dev', 'stage', 'prod']
SECTION ->  dev
-------------------
LOG_FILE_PATH -  /opt/logs/app.log
SECRET_KEY -  DEV_SECRET_KEY
SECRET_VALUE -  DEV_SECRET_VALUE
PORT -  8080
APP_BASE_URL -  dev.myapp.com
IS_DEBUG -  True
SECTION ->  stage
-------------------
LOG_FILE_PATH -  /opt/logs/app.log
SECRET_KEY -  STAGE_SECRET_KEY
SECRET_VALUE -  STAGE_SECRET_VALUE
PORT -  8088
APP_BASE_URL -  stage.myapp.com
IS_DEBUG -  False
SECTION ->  prod
-------------------
LOG_FILE_PATH -  /opt/app/logs/app.log
SECRET_KEY -  PROD_SECRET_KEY
SECRET_VALUE -  PROD_SECRET_VALUE
PORT -  8000
APP_BASE_URL -  myapp.com
IS_DEBUG -  False
More on ConfigParser
Python command-line arguments
Happy Learning 🙂

Pandas read_excel – Read Excel files in Pandas
Python How to read input from keyboard
Python raw_input read input from keyboard
How to read a text file in Python ?
How to read JSON file in Python ?
How to Read CSV File in Python
Java 8 walk How to Read all files in a folder
Python read data from MySQL Database
Python – How to Read Google Search Results in Selenium
Pandas read_csv – Read CSV file in Pandas and prepare Dataframe
How to Delete a File or Directory in Python
Python – How to create Zip File in Python ?
How to Remove Spaces from String in Python
How to do Multiprocessing in Python
How to get Words Count in Python from a File

Pandas read_excel – Read Excel files in Pandas
Python How to read input from keyboard
Python raw_input read input from keyboard
How to read a text file in Python ?
How to read JSON file in Python ?
How to Read CSV File in Python
Java 8 walk How to Read all files in a folder
Python read data from MySQL Database
Python – How to Read Google Search Results in Selenium
Pandas read_csv – Read CSV file in Pandas and prepare Dataframe
How to Delete a File or Directory in Python
Python – How to create Zip File in Python ?
How to Remove Spaces from String in Python
How to do Multiprocessing in Python
How to get Words Count in Python from a File
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list