Python ConfigParser Introduction














































Python ConfigParser Introduction



INTRODUCTION TO ConfigPaser

 

ConfigParser-configuration file parser:-

ConfigParser the module provides the ConfigParser class
which implements a basic configuration language that provides a structure
similar to whats found in Microsoft Windows INI files.

Python ConfigParser the module is an extremely
important one
 when it comes to creating configurable applications.

NOTE:- This library does not interpret or write the value-type prefixes
used in the Windows Registry extended version of INI syntax.

v Purpose:-

1. To Read configuration file similar to INI windows files.

2. To write a configuration file similar to INI windows files.

   What can the Does config file include?

The config files we create can contain integer values, floating-point values, and Boolean
values.

important points know to use config files follow:

1. 
 The config file sections can be identified by having lines starting with [ and ending with ]. Between square brackets, we can put the sections name, the sections name can contain any character except square bracket itself.

2.    Lines starting with ; or # are treated as comments and are not available programmatically.

The values are separated by a = or a:

 

Let's take a look at one example of the config file.

 

# and ; are comments which can
contain anything.

[database_config]

url = https://localhost:3306/mysql/

username = root

; Consider hashing this password
rather than

; keeping it as plain-text here

password = MY_PASSWORD

See, how easy was that! The values which can be
used programmatically in the above files are URL, username and password.

Let's see how It is implemented using the program.

1. 1. First, we have to define config file.

# and ; are comments which can
contain anything.

[database_config]

url = https://localhost:3306/mysql/

username = root

; Consider hashing this password
rather than

; keeping it as plain-text here

password = MY_PASSWORD

save this file as database.config and keep this file in the same directory where we write the next code also.

2. Now we have to write python code to access the database.config using confingpaser module.

; importing ConfigParser from
configparser module.

from configparser import ConfigParser

parser = ConfigParser()

; reading data from database.config
file.

parser.read('database.config')

; printing key value using the key
from
 database.config file

print(parser.get('database_config''url'))

save the above file as simple_config_access.py in the same directory.

3.    Let's see the Output.


This was pretty simple actually.

 

 



Comments