假设config.ini的内容如下
[server]
host = 127.0.0.1
port = 8000
[database]
name = test
user = test
password = password
host = 127.0.0.1
port = 3306
[log]
dir = /some/path
继承configparser
import configparser
from pathlib import Path
class Conf(configparser.ConfigParser):
def __init__(self, filename=None):
super().__init__()
if filename:
self.filename = filename
else:
self.filename = ‘config/config.ini‘
self.read(self.filename, encoding=‘utf-8‘)
def getpath(self, section, option):
# 获取路径配置
return Path(self.get(section=section, option=option)) # pathlib标准库可以解决夸平台路径斜杠不一样的问题
def write(self, fp=None, space_around_delimiters: bool = ...) -> None: # 重载write
fp = open(self.filename, "w")
super().write(fp=fp)
from tools.config import Conf
conf = Conf() # 实例化对象
conf.get(‘server‘, ‘host‘)
# 127.0.0.1
conf.getpath(‘log‘, "dir")
# /some/path, 这个方法是自定义的
conf.getint(‘database‘, ‘port‘)
# 获取ini类型的值,3306
# 还有getboolean和getfloat
,是一样的用法
conf.sections()
# 获取所有配置合集的名称, [‘server‘, ‘database‘, ‘log‘]
conf.items(‘server‘)
# [(‘host‘, ‘127.0.0.1‘), (‘port‘, ‘8000‘)]
# 获取server配置下的配置项
conf.options(‘server‘)
# [‘host‘, ‘port‘]
# 获取配置集下的配置项
conf.add_section(‘test‘)
# 添加配置集合
conf.set(‘server‘, ‘host‘, ‘127.0.0.2‘)
# 添加或者设置host,server必须存在
conf.remove_section(‘server‘)
# 删除server
conf.remove_option(‘server‘, ‘host‘)
# 删除host
conf.writer()
# 只有write之后上面的修改才会生效
# 这里这个write已经被重载,原来的写法应该为conf.writer(open("some_config.ini", "w"))
原文:https://www.cnblogs.com/huangyuechujiu/p/14383629.html