Python 配置文件详解(configparser)

1 概述

1.1 configparser 内置模块

  • configparser :配置解析器
  • Python 自带模块,无需再次安装

1.2 配置格式

  • 文件格式*.ini
  • 内容格式:同下图
  • 注意事项:获取 *.ini 中的信息时,会自动转为小写哦

在这里插入图片描述

例如:config.ini 中内容如下

[login]
userName = admin
password = 123456

[person]
name = 张三
age = 18
sex =

1.3 简单应用

import configparser

# 声明配置类对象
config = configparser.ConfigParser()

# 配置文件名
fileName= 'config.ini'

# 读取配置文件
config.read(fileName, 'GBK')
print(f"sections: {config.sections()}")
print(f"options: {config.options('login')}")
print(f"items: {config.items('login')}")

执行结果:

sections: ['login', 'person']
options: ['username', 'password']
items: [('username', 'admin'), ('password', '123456')]

2 常用方法

2.1 读取

2.1.1 读取段:section()

import configparser


class Config(object):
    def __init__(self, filename, encoding):
        # 声明配置类对象
        self.config = configparser.ConfigParser()
        # 读取配置文件
        self.config.read(filename, encoding)

    def get_section(self):
        """获取 section"""
        for i in self.config.sections():
            print(f'section: {i}')


if __name__ == '__main__':
    test = Config('config.ini', 'UTF-8')
    test.get_section()

执行结果:

section: login
section: person

2.1.2 读取选项:options()

import configparser


class Config(object):
    def __init__(self, filename, encoding):
        # 声明配置类对象
        self.config = configparser.ConfigParser()
        # 读取配置文件
        self.config.read(filename, encoding)

    def get_options(self, section):
        """获取 option"""
        for i in self.config.options(section):
            print(f'option: {i}')


if __name__ == '__main__':
    test = Config('config.ini', 'UTF-8')
    test.get_options('login')

执行结果:

option: username
option: password

2.1.4 读取选项值:get()

import configparser


class Config(object):
    def __init__(self, filename, encoding):
        # 声明配置类对象
        self.config = configparser.ConfigParser()
        # 读取配置文件
        self.config.read(filename, encoding)

    def get_value(self, section, option):
        """获取 value"""
        value = self.config.get(section, option)
        print(f'value: {value}')


if __name__ == '__main__':
    test = Config('config.ini', 'UTF-8')
    test.get_value('login', 'username')

执行结果:

admin

2.1.3 读取项目:items()

import configparser


class Config(object):
    def __init__(self, filename, encoding):
        # 声明配置类对象
        self.config = configparser.ConfigParser()
        # 读取配置文件
        self.config.read(filename, encoding)

    def get_items(self, section):
        """获取 items"""
        for key, value in self.config.items(section):
            print(f"option: {key}")
            print(f"value: {value}")
            print()


if __name__ == '__main__':
    test = Config('config.ini', 'UTF-8')
    test.get_items('login')

执行结果:

option: username
value: admin

option: password
value: 123456

2.2 新增

2.2.1 新增段:add_section()

import configparser


class Config(object):
    def __init__(self, filename, encoding):
        # 声明配置类对象
        self.config = configparser.ConfigParser()
        # 声明配置文件
        self.filename = filename
        # 声明编码格式
        self.encoding = encoding
        # 读取配置文件
        self.config.read(filename, encoding)

    def add_section(self, section):
        if not self.config.has_section(section):
            self.config.add_section(section)

        self.write_config(self.filename, self.encoding)

    def write_config(self, filename, encodeing):
        with open(filename, 'w', encoding=encodeing) as f:
            self.config.write(f)


if __name__ == '__main__':
    test = Config('config.ini', 'UTF-8')
    test.add_section('database')

执行结果:

[login]
username = admin
password = 123456

[person]
name = 张三
age = 18
sex =[database]

2.2.2 新增项目:set()

import configparser


class Config(object):
    def __init__(self, filename, encoding):
        # 声明配置类对象
        self.config = configparser.ConfigParser()
        # 声明配置文件
        self.filename = filename
        # 声明编码格式
        self.encoding = encoding
        # 读取配置文件
        self.config.read(filename, encoding)

    def add_items(self, section, option, value):
        # 前提:不存在 option 时
        if not self.config.has_option(section, option):
            # set:设置值(新增 或 修改)
            self.config.set(section, option, value)

        # 写入
        self.write_config(self.filename, self.encoding)

    def write_config(self, filename, encodeing):
        with open(filename, 'w', encoding=encodeing) as f:
            self.config.write(f)


if __name__ == '__main__':
    test = Config('config.ini', 'UTF-8')
    test.add_items('database', 'host', '127.0.0.1:1521')

执行结果:config.ini 文件内容

[login]
username = admin
password = 123456

[person]
name = 张三
age = 18
sex =[database]
host = 127.0.0.1:1521

2.3 修改

2.3.1 修改选项值:set()

import configparser


class Config(object):
    def __init__(self, filename, encoding):
        # 声明配置类对象
        self.config = configparser.ConfigParser()
        # 声明配置文件
        self.filename = filename
        # 声明编码格式
        self.encoding = encoding
        # 读取配置文件
        self.config.read(filename, encoding)

    def update_values(self, section, option, value):
        # 前提:存在 option 时
        if self.config.has_option(section, option):
            # 修改值
            self.config.set(section, option, value)

        # 写入
        self.write_config(self.filename, self.encoding)

    def write_config(self, filename, encodeing):
        with open(filename, 'w', encoding=encodeing) as f:
            self.config.write(f)


if __name__ == '__main__':
    test = Config('config.ini', 'UTF-8')
    test.update_values('database', 'host', '192.168.200.2:1521')

执行结果:

[login]
username = admin
password = 123456

[person]
name = 张三
age = 18
sex =[database]
host = 192.168.200.2:1521

2.4 删除

2.4.1 删除段:remove_section()

  • 注:删除段:remove_section() 时,段内的 项目,也会被删除
import configparser


class Config(object):
    def __init__(self, filename, encoding):
        # 声明配置类对象
        self.config = configparser.ConfigParser()
        # 声明配置文件
        self.filename = filename
        # 声明编码格式
        self.encoding = encoding
        # 读取配置文件
        self.config.read(filename, encoding)

    def remove_section(self, section):
        # 删除
        self.config.remove_section(section)

        # 写入
        self.write_config(self.filename, self.encoding)

    def write_config(self, filename, encodeing):
        with open(filename, 'w', encoding=encodeing) as f:
            self.config.write(f)


if __name__ == '__main__':
    test = Config('config.ini', 'UTF-8')
    test.remove_section('database')

2.4.2 删除选项:remove_option()

import configparser


class Config(object):
    def __init__(self, filename, encoding):
        # 声明配置类对象
        self.config = configparser.ConfigParser()
        # 声明配置文件
        self.filename = filename
        # 声明编码格式
        self.encoding = encoding
        # 读取配置文件
        self.config.read(filename, encoding)

    def remove_option(self, section, option):
        if self.config.has_option(section, option):
            self.config.remove_option(section, option)

        # 写入
        self.write_config(self.filename, self.encoding)

    def write_config(self, filename, encodeing):
        with open(filename, 'w', encoding=encodeing) as f:
            self.config.write(f)


if __name__ == '__main__':
    test = Config('config.ini', 'UTF-8')
    test.remove_option('person', 'sex')
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼丸丶粗面

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值