Python parsing configuration file ini

Reference article

Introduction to the configparser module

Detailed explanation of python's configparser module

ini configuration file

The format of the configuration file is as follows: Sections contained in brackets "[ ]". The following is the configuration content similar to the key-value. The key of each section can be the same.

# 数据库配置
[db]
host = 192.168.1.133
port = 3306
name = shop
password = 123123

# redis 配置
[redis]
host = 192.168.1.136
port = 6300
password = yes

Generate configuration file

# 初始化配置危机
def init_config():
    config = configparser.ConfigParser()

    config["db"] = {
    
    "host": "192.168.1.133",
                    "port": "3306",
                    "name": "shop",
                    "password": "123123"
                    }  # 类似于操作字典的形式

    config["redis"] = {
    
    "host": "192.168.1.136",
                       "port": "3309",
                       "password": "redis"
                       }

    with open("example.ini", "w", encoding="UTF-8") as configfile:
        config.write(configfile)  # 将对象写入文件

Operation result: The configuration file example.ini is generated, and the content is as follows.

[db]
host = 192.168.1.133
port = 3306
name = shop
password = 123123

[redis]
host = 192.168.1.136
port = 3309
password = redis

Read configuration

# 读取配置文件
def read_config():
    config = configparser.ConfigParser()
    config.read("example.ini", encoding="UTF-8")

    # 获取指定key的value
    # 方式一
    db_host = config["db"]["host"]
    redis_host = config["redis"]["host"]

    print("db_host = %s " % db_host)
    print("redis_host = %s " % redis_host)

    # 方式二
    db_port = config.get("db", "port")
    redis_port = config.get("redis", "port")

    print("db_port = %s " % db_port)
    print("redis_port = %s " % redis_port)

    # 方式三 . getint,getboolean,getfloat
    db_port = config.getint("db", "port")
    redis_port = config.getint("redis", "port")
    print("db_port = %s " % db_port)
    print("redis_port = %s " % redis_port)

    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    # 判断 section 是否存在
    flag = config.has_section("redis")
    print(flag)

    flag = config.has_section("mq")
    print(flag)

    # 判断 ption 是否存在
    flag = config.has_option("redis", "host")
    print(flag)

    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    # 获取 sections
    sections = config.sections()
    print(sections)

    # 获取 section 的 key 集合
    options = config.options("db")
    print(options)

    # 获取 section 的 key-value 集合
    items = config.items("db")
    print(items)

operation result:

db_host = 192.168.1.133 
redis_host = 192.168.1.136 
db_port = 3306 
redis_port = 3309 
db_port = 3306 
redis_port = 3309 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
True
False
True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
['db', 'redis']
['host', 'port', 'name', 'password']
[('host', '192.168.1.133'), ('port', '3306'), ('name', 'shop'), ('password', '123123')]

Change setting

def update_config():
    config = configparser.ConfigParser()
    config.read("example.ini", encoding="UTF-8")

    # 添加配置
    config.add_section("file")
    config.set("file", "max_size", "10000")
    config.set("file", "extend", ".img,.xml")

    # 修改配置
    config.set("redis", "port", "6379")

    # 删除配置
    config.remove_option("redis", "password")

    with open('example.ini', 'w') as config_file:
        config.write(config_file)

As a result, the example.ini file is as follows:

[db]
host = 192.168.1.133
port = 3306
name = shop
password = 123123

[redis]
host = 192.168.1.136
port = 6379

[file]
max_size = 10000
extend = .img,.xml

The difference between RawConfigParser and ConfigParser

RawConfigParser is the most basic INI file reading class. ConfigParser and SafeConfigParser support the analysis of %(value)s variables

ini add content

[message]
name=小明
age=27
detail= name is %(name)s age is %(age)s
def raw_config_parser():
    config = configparser.ConfigParser()
    config.read("example.ini", encoding="UTF-8")

    print("~~~~~~~~~~ConfigParser~~~~~~~~~~~~")
    name = config["message"]["name"]
    age = config["message"]["age"]
    detail = config["message"]["detail"]

    print("name = %s , age = %s , detail = %s"% (name, age, detail))

    config = configparser.RawConfigParser()
    config.read("example.ini", encoding="UTF-8")

    print("~~~~~~~~~~ConfigParser~~~~~~~~~~~~")
    name = config["message"]["name"]
    age = config["message"]["age"]
    detail = config["message"]["detail"]

    print("name = %s , age = %s , detail = %s"% (name, age, detail))

operation result:

~~~~~~~~~~ConfigParser~~~~~~~~~~~~
name = 小明 , age = 27 , detail = name is 小明 age is 27
~~~~~~~~~~ConfigParser~~~~~~~~~~~~
name = 小明 , age = 27 , detail = name is %(name)s age is %(age)s

Guess you like

Origin blog.csdn.net/fangye1/article/details/112170418