Social Icons

Thursday, March 5, 2020

The configparser module

1 - The configparser module 

The Python language has a module called configparser which allows you to use and manipulate configuration files similar to Windows files of .ini type. The configparser module can be used to manage user-configurable configuration files within an application. The content of a configuration file can be organized into sections containing each of the parameters with associated values. Several types of option values ​​are supported, including integers, floating point values, and booleans.

2 - Installation of the configparser module 

Nothing more simple to install the configparser module, just type on the command line:
 pip install config-parser

3 - Format of the configuration file 

The file format used by configparser is similar to that used by older versions of Microsoft Windows. It consists of one or more named sections, each of which may contain options with names and values.
  1. The configuration file sections are identified by looking for lines starting with '[' and ending with ' ] '. The value between the brackets indicates the name of the section and can contain all the characters except the brackets. 
  2. The options are listed one per line in a section. 
  3. The line starts with the name of the option, which is separated from the value by  ":" or an equal sign "=" 
  4. Comments: are lines starting with a semicolon ';' Or a hash " # " and are treated as comments and are not visible when accessing the contents of the configuration file. 
 
The following example in the configuration file has a section called settings with three options, host, username and password:
# Server configuration settings
[settings]
host :  127.0.0.1 
username :  root
password :  root 

4- Reading the value of an option from an .ini configuration file in Python

With the Python language we can use the configparser module and the read () method of the ConfigParser object to read the configuration file:

Example. Reading the configuration.ini file in Python

from configparser import ConfigParser
parser = ConfigParser ()
parser.read ('configuration.ini') 

# Display the 'host' parameter value  
print (parser.get ('settings', 'host'))
# The output is: 127.0.0.1
 

5 - Update the parameter of a section


To update a parameter in the configuration file, you must first open it in read and write mode and then use the set() method of the ConfigParser class.

Example. update the value of the parameter 'host'

from configparser import ConfigParser
parser = ConfigParser ()
parser.read ('configuration.ini')

# Open the configuration file in read and write mode
file = open ('configuration.ini', 'r+')

# update the value of the 'host' parameter
parser.set ('settings', 'host', 'localhost')
parser.write (file)
file.close ()
 
Now if you open the configuration.ini file, you will see that the parameter:
host = 127.0.0.1 
has become:
host = localhost

6 - Reading the sections of a configuration file 

The sections() method of the parser object allows you to retrieve the sections of the configuration file in object of a list type:

Example. configuration.ini

[settings]
# server configuration parameters
host      : 127.0.0.1
username  : root
password  : root

[Safe_Mode]
# http://php.net/safe-mode
safe_mode = Off
safe_mode_gid = on

[File_Uploads]
# http://php.net/file-uploads
file_uploads = On
upload_tmp_dir = "c:/wamp/tmp"
upload_max_filesize = 20M

Example. reading sections of the configuration.ini file

from configparser import ConfigParser
parser = ConfigParser() 
parser.read('configuration.ini') 
sec = parser.sections() 
print(sec) 
# The output is: ['settings', 'Safe_Mode', 'File_Uploads']

7 - Read the list of options with the options() method


The options() method of the ConfigParser object allows you to retrieve the list options in a section of the configuration file:

Example. The list  options in the first section:

from configparser import ConfigParser
parser = ConfigParser()
parser.read ('configuration.ini')
# getting the first section
sec = parser.sections()[0]
# get the list of options
print (sec, parser.options(sec)) 
# The output is: settings ['host', 'username', 'password']
 
Now by using the for loop statement, we can get all sections with their options:

Example. List of all sections with their options: 

from configparser import ConfigParser
parser = ConfigParser()
parser.read('configuration.ini')

# Browse all sections
for sec in parser.sections():
     # cycle through options in different sections
     print (sec, ":", parser.options (sec))
The output is:
settings: ['host', 'username', 'password']
Safe_Mode: ['safe_mode', 'safe_mode_gid']
File_Uploads: ['file_uploads', 'upload_tmp_dir', 'upload_max_filesize']

8 - Total reading with the items() method 

The items() method allows you to retrieve the names of the parameters with their values:

Example. retrieving the parameters and values ​​from the first section

from configparser import ConfigParser
parser = ConfigParser ()
parser.read ('configuration.ini')

# Point to the first section
sec = parser.sections()[0]
print (sec, ":")
for name, value in parser.items(sec):
    print(name, value) 
Full display of sections with their parameters and values:
from configparser import ConfigParser
parser = ConfigParser ()
parser.read ('configuration.ini')

# Browse sections
for sec in parser.sections ():
    print (sec, ":")
    # browse parameters and values
    for name, value in parser.items (sec):
        print(name, value) 
The output is:
settings:
  host = 127.0.0.1
  username = root
  password = root
Safe_Mode:
  safe_mode = Off
  safe_mode_gid = on
File_Uploads:
  file_uploads = On
  upload_tmp_dir = "c:/wamp/tmp"
  upload_max_filesize = 20M

9 - Adding a section with the add_section() method 

 With the add_section() method of the ConfigParser class, you can add as many sections as you want, for that you must first open the configuration file in read and write mode and then use the set () method of the ConfigParser class  to be able to define and add new options to the section.

Example. Adding a section named mysqld

from configparser import ConfigParser
parser = ConfigParser()
parser.read ('configuration.ini')

# Opening the configuration file
file = open('configuration.ini', 'r+')

# Adding a new mysqld section
parser.add_section ('mysqld')
# Definition and addition of new options
parser.set('mysqld', 'port', '3306')
parser.set('mysqld', 'table_cache', '64')
parser.write(file)
file.close()
After executing the code, you will see a new section [mysqld] which is added to the configuration.ini file:

[settings]
host = 127.0.0.1
username = root
password = root

[Safe_Mode]
safe_mode = Off
safe_mode_gid = on

[File_Uploads]
file_uploads = On
upload_tmp_dir = "c:/wamp/tmp"
upload_max_filesize = 20M

[mysqld]
port = 3306
table_cache = 64




 Younes Derfoufi
my-courses.net

No comments:

Post a Comment

Category Of Mobile Courses

Actualités (644) Adsense (1) Affiliation (1) Algebraic Topology (1) Algorithmic (1) all-news (30) Android (5) Android App (8) Android app without code (4) Android Apps (169) Android Development (4) Android download (2) Android OS (3) AngularJS (1) Automata theory and formal language (5) C programming (5) Category and Functor (8) CMS (3) Computer Glossary (18) Create Mobile App With Ionic Framework (2) CSS (2) CSS-Cascading-Style-Sheets (4) Developpement Java (13) Differential Geometry (1) Django-Python-Framework (8) dropshiping (26) Earn Money by Internet (4) Emplois (23) Framework php (2) Fraud (2) HTML (7) Java For Beginners (10) Javascript (12) Kotlin Programming Language (8) Kotlin For Mobile Android (1) Linux Download (2) Marketing (5) Mobile (3) Mobile Courses (4) Mobile Marketing (4) MoneyGram (1) News (721) Node.js (5) Open Source (1) Photoshop (1) Protect Computer (1) Python (33) Python BeautifulSoup (1) Python For Data Science (2) Python-Books (6) Python-DVD-Training (1) Python-Exercises (140) Python-Framework (1) Python-IDE (1) Python-Modules (1) Python-pdf (2) Python-pyQt (1) Référencement (2) Script PHP (2) Security (6) SEO (1) Snipping Tool: Faq (1) Social Networks (1) Source Code (1) Statistics With SPSS (2) Surveillance Software (1) Travail à domicile (6) Tutoriels php en vidéos (2) Tutoriels-MySql (6) tutoriels-php (19) Utilitaires (1) VPS (1) Web Hosting (1) Webcam (1) Webmarketing (11) Western Union (1) Windows 10 (1) Windows 7 (4) Windows 7 Faq (2) Windows 8 (1) Windows Accessories (1) Windows Download (8) Windows Drivers (1) Windows Fonts (1) Windows Power Shell (2) Windows Registry (2) Windows Security (18) Windows Software (2) Windows Spyware (2) Windows utilities (3) Windows Virus (2) Windows Vista (3) Windows Wireless (1) Windows xp (1) Wordpress (1)
 

Sample text

Sample Text

 
Blogger Templates