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_port = 3306
db_user = root
db_host =
db_pass = xgmtest
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True
FavoriteColor = Green
FamilyName: Johnson
Route: 66

How do I read it in Python

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

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


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:

import ConfigParser
config = ConfigParser.ConfigParser(allow_no_value=True)"hosts.txt")
print config.items("zone2")

Operation results:

$ ./ 
[('', None), ('', None), ('', None)]

Related articles: