首页 > 编程语言 > 详细

python3标准库configparser的使用

时间:2021-02-07 09:49:41      阅读:32      评论:0      收藏:0      [点我收藏+]

python3标准库configparser的使用


0. 假设的项目目录

技术分享图片

1.config.ini

假设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

2.config.py

继承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)

3.读配置

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‘]
# 获取配置集下的配置项

4.写配置


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"))


更多参考python:configparser模块

python3标准库configparser的使用

原文:https://www.cnblogs.com/huangyuechujiu/p/14383629.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!