python_configparser模块

前言

  • configparser是Python标准库中的一个模块,用于解析和操作配置文件。它提供了读取和写入常见配置文件格式的功能。
  • configparser模块主要支持写入 INI 文件格式。INI文件格式是一种常见的配置文件格式,它由节(section)和键值对(key-value)组成。每个键值对位于一个节内,节用方括号 []表示,键值对由键和值组成。

一、写入

import configparser

# 创建一个 ConfigParser 对象
config = configparser.ConfigParser()

# 方法一
# 添加新的节点(section)名称
config.add_section('new_section')
# 添加配置选项-键(option)和对应的值(value)
config.set('new_section', 'option_name', 'value')

# 方法二
config['Database'] = {
    'host': 'localhost',
    'port': '3306',
    'username': 'admin',
    'password': 'secret'
}

# 写入配置文件,编码格式utf-8
with open('config.ini', 'w', encoding='utf-8') as configfile:
    config.write(configfile)

在这里插入图片描述

二、读取

import configparser

# 创建一个 ConfigParser 对象
config = configparser.ConfigParser()

# 读取名为 'config.ini' 的配置文件,并将其内容解析到 config 对象中
config.read('config.ini')

# 返回配置文件中的所有节点(sections)的列表
sections = config.sections()
print(sections)

# 返回 'Database' 节点中的所有配置项(options)的列表
options = config.options('Database')
print(options)

# 返回 'Database' 节点中的所有配置项和对应值的键值对组成的列表
items = config.items('Database')
print(items)

# 返回 'Database' 节点中 'host' 配置项的值
value = config.get('Database', 'host')
print(type(value), value)

在这里插入图片描述

三、修改

import configparser

# 创建一个 ConfigParser 对象
config = configparser.ConfigParser()

# 读取名为 'config.ini' 的配置文件,并将其内容解析到 config 对象中
config.read('config.ini')

# 修改节点(section)名称
# 通过 config.sections() 方法获取所有的节点(section)名称,并选择要修改的节点名称
sections = config.sections()
old_section_name = 'Database'  # 要修改的节点名称

# 使用 config.add_section() 方法添加一个新的节点(section),将节点的键值对复制到新节点中
config.add_section('mysql')
for key, value in config.items(old_section_name):
    config.set('mysql', key, value)

# 使用config.remove_section() 方法删除旧的节点
config.remove_section('Database')  # 删除原有的节
# ----------------------------------

# 修改配置选项-键(option)
section_name = 'mysql'  # 要修改的节点名称
old_option_name = 'username'  # 现有的配置选项名称

# 获取现有的配置选项的值
old_value = config.get(section_name, old_option_name)

# 使用 config.remove_option() 方法删除现有的配置选项
config.remove_option(section_name, old_option_name)

# 使用 config.set() 方法添加一个新的配置选项,并将其设置为之前的值
new_option_name = 'user'     # 新的配置选项名称
config.set(section_name, new_option_name, old_value)
# -------------------------------

# 修改value值
section_name = 'mysql'  # 要修改的节点名称
option_name = 'user'    # 要修改的配置选项名称

new_value = 'root'  # 新的配置值
config.set(section_name, option_name, new_value)

# 将修改后的配置写回到文件中
with open('config.ini', 'w') as configfile:
    config.write(configfile)

在这里插入图片描述

四、删除

import configparser

# 创建一个 ConfigParser 对象
config = configparser.ConfigParser()

# 读取名为 'config.ini' 的配置文件,并将其内容解析到 config 对象中
config.read('config.ini')

# 删除节点(section)
# 使用config.remove_section() 方法删除节点
config.remove_section('new_section')

# 删除配置选项-键(option)
# 使用 config.remove_option() 方法删除配置选项
config.remove_option('mysql', 'user')

# 将修改后的配置写回到文件中
with open('config.ini', 'w') as configfile:
    config.write(configfile)

在这里插入图片描述

五、封装示例

import configparser


class ConfigFile:
    """
    使用configparser模块读写INI格式配置文件的类
    """

    def __init__(self, file_path, encoding):
        """
        初始化方法,传入配置文件路径
        :param file_path: 配置文件路径
        :param encoding: 配置编码格式
        """
        self.file_path = file_path
        self.encoding = encoding

    def read(self):
        """
        读取配置文件内容
        :return: 返回一个字典,键为节名,值为字典,键为选项名,值为选项值
        """
        config = configparser.ConfigParser()
        config.read(self.file_path, encoding=self.encoding)
        return {section: dict(config.items(section)) for section in config.sections()}

    def write(self, data_dict):
        """
        写入配置文件内容
        :param data_dict: 字典类型数据,包含配置文件内容
        """
        config = configparser.ConfigParser()
        for section, options in data_dict.items():
            config.add_section(section)
            for option, value in options.items():
                config.set(section, option, value)

        with open(self.file_path, 'w', encoding=self.encoding) as f:
            config.write(f)

    def update(self, section, data_dict, new_section=None):
        """
        更新配置文件指定节的内容
        :param section: 节名
        :param data_dict: 字典类型数据,包含要更新的选项及其值
        :param new_section: 新的节名,如果为None,则不修改节名
        """
        config = configparser.ConfigParser()
        config.read(self.file_path, encoding=self.encoding)
        if not config.has_section(section):
            config.add_section(section)

        for option, value in data_dict.items():
            config.set(section, option, value)

        if new_section is not None:
            # 修改节名
            config.add_section(new_section)
            for option, value in data_dict.items():
                config.set(new_section, option, value)
            config.remove_section(section)

        with open(self.file_path, 'w', encoding=self.encoding) as f:
            config.write(f)

    def delete(self, section, option=None):
        """
        删除配置文件指定节或选项
        :param section: 节名
        :param option: 选项名,如果为None,则删除整个节
        """
        config = configparser.ConfigParser()
        config.read(self.file_path, encoding=self.encoding)
        if config.has_section(section):
            if option is None:
                config.remove_section(section)
            else:
                config.remove_option(section, option)

            with open(self.file_path, 'w', encoding=self.encoding) as f:
                config.write(f)
        else:
            print("节点不存在!")


if __name__ == "__main__":
    # 实例化一个ConfigFile对象
    config = ConfigFile('example.ini', 'UTF-8')

    # 写入配置文件内容
    new_data_dict = {
        'web_server': {
            'host': '127.0.0.1',
            'port': '8080'
        },
        'user_information': {
            'account': 'admin',
            'password': '123'
        }
    }
    config.write(new_data_dict)

    # 读取配置文件内容
    data_dict = config.read()
    print(data_dict)
    print(data_dict['web_server']['port'])

    # 更新配置文件内容
    update_data_dict = {
        'host': 'localhost',
        'port': '8888'
    }
    config.update('web_server', update_data_dict, new_section='new_web_server')

    # 删除配置文件内容
    config.delete('new_web_server', 'host')

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值