Python read profile module ConfigParser

  • 2020-06-01 10:08:45
  • OfStack

1. Introduction to ConfigParser module

Suppose you have the following configuration file that you need to read in the Pyhton program


$ cat config.ini
[db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = xgmtest
 
[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True
 
[SectionTwo]
FavoriteColor = Green
[SectionThree]
FamilyName: Johnson
 
[Others]
Route: 66

How do I read it in Python


>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("config.ini")
['config.ini']
>>> Config.sections()
['db', 'Others', 'SectionThree', 'SectionOne', 'SectionTwo']
>>> Config.get("db", "db_host")
'127.0.0.1'
>>> Config.getint("db", "db_port")
3306

2. Introduction to the basic methods of ConfigParser module

Read the configuration file


read(filename)  Directly read ini The file content 
sections()  Get all of section And return it as a list 
options(section)  Get the section All of the option
items(section)  Get the section All key value pairs 
get(section,option)  get section In the option Is returned as string type 
getint(section,option)  get section In the option Is returned as int The type, and the corresponding getboolean() and getfloat()  function 

Write configuration file


add_section(section)  add 1 A new one section
set(section, option, value)  right section In the option To set it up, you need to call write Write to the configuration file 

3. Special circumstances

If you have the following configuration files


[zone1]
192.168.10.13
192.168.10.15
192.168.10.16
192.168.10.17
[zone2]
192.168.11.13
192.168.11.14
192.168.11.15
[zone3]
192.168.12.13
192.168.12.14
192.168.12.15

This configuration file, for each section, is not in the form of a key value pair. If you call ConfigParser to read it, the following error will be reported:


ConfigParser.ParsingError: File contains parsing errors: hosts.txt

Therefore, the correct method is:


#!/usr/bin/python
 
import ConfigParser
 
config = ConfigParser.ConfigParser(allow_no_value=True)
config.read("hosts.txt")
print config.items("zone2")

Operation results:


$ ./a.py 
[('10.189.22.21', None), ('10.189.22.22', None), ('10.189.22.23', None)]

Related articles: