python configparser操作配置文件

一、configparser概述

configparser 是 Pyhton 标准库中用来解析配置文件的模块;Python2.x 中名为 ConfigParser,3.x 已改名为configParser

二、配置文件的格式

常见的配置文件后缀:.ini.conf等,主要结构为包括以下的文本信息:

  1. sections(段)
  2. keys(properties\键)
  3. values(值)

格式如下:

[section]
key1=value1
key2=value2

配置文件示例 db_config.ini:

[oracle]
host = localhost
user = oracle_user
passwd = 123456
db = ora_db

[mysql]
host = localhost
user = root
passwd = 123456
db = testdb

[postgresql]
host = localhost
user = test
passwd = 123456
db = pgsql_db

三、读取文件内容

#coding=utf-8
import configparser


conf = configparser.ConfigParser()  # 初始化实例
conf.read('db_config.ini')   # 加载读取配置文件

# 获取所有 sections 名称
sections = conf.sections()  # list: ['oracle', 'mysql', 'postgresql']

# 获取指定 section 的 keys
option = conf.options("mysql")  # list: ['host', 'user', 'passwd', 'db']

# 获取 指定 section 指定 key 的 value 值
value = conf.get('logoninfo', 'addr') # str: testdb

# 获取指定 section 的 keys & values
item = conf.items('mysql')  # list: [('host', 'localhost'), ('user', 'root'), ('passwd', '123456'), ('db', 'testdb')]

print('mysql' in conf)  # 检查section是否存在
print("db" in conf["mysql"]) # 检查section中的key是否存在

四、写入配置文件

import configparser                     # 引入模块

conf = configparser.ConfigParser()    #实例化一个对象

conf['sqlserver'] = {
    'host': '127.0.0.1',
    'port': '1433',
    'user': 'root',
    'password': '123456',
    'db': 'my_db'
}

conf.set('mysql', 'port', '3306')  # 添加一个sectiond 的key=value配置项
conf.set('oracle', 'host', '192.168.1.5')  # 修改一个配置项
conf.remove_option("mysql", "db")  # 删除指定sectiond 的key=value配置项
config.remove_section("postgresql")  # 删除指定sectiond

with open('db_config.ini', 'w') as wf:
    conf.write(wf)

# 重命名section
def rename_section(config, old_section, new_section):
    items = config.items(old_section)
    print(items)
    if not config.has_section(new_section):
        config.add_section(new_section)
    # 将原始 section 的内容写入新的 section
    for key, value in items:
        config.set(new_section, key, value)

    config.remove_section(old_section)
    
    with open('db_config.ini', 'w') as wf:
        conf.write(wf)
    
# 调用重命名方法
rename_section(conf, old_section='mysql', new_section='sqlite')

posted @ 2024-08-22 10:16  二月雪  阅读(3)  评论(0编辑  收藏  举报