Python读写配置文件模块--Configobj

复制代码
from configobj import ConfigObj
import os


# Python读写配置文件模块--Configobj
class TestConfig():

    def __init__(self):
        self.path = os.path.dirname(os.path.dirname(__file__)) + "/config/config.ini"
        print(self.path)
        # 实例化一个Configobj对象,给ConfigObj一个配置文件的路径,然后通过字典来访问成员,子段也是一个字典
        self.config = ConfigObj(self.path, encoding='UTF-8')

    # 读取配置文件信息
    def query_config(self):
        print(self.config['HJ'])
        print(self.config['HJ']['hj'])

    # 给配置文件添加新项
    def add_config(self):
        self.config['data'] = {}
        self.config['data']['user'] = 'root'
        self.config.write()

    # 修改配置文件
    def modify_config(self):
        print(self.config['HJ']['hj'])
        self.config['HJ']['hj'] = 'regression'
        self.config.write()

        print(self.config['HJ']['hj'])
        self.config['HJ']['hj'] = 'maoyan'

        self.config.write()
        print(self.config['HJ']['hj'])

    # 删除配置文件中的某个项
    def del_config(self):
        del self.config['data']['user']
        del self.config['data']
        self.config.write()

    # 将配置文件写入到不同的文件
    def write_other_file(self):
        self.config.filename = os.path.dirname(os.path.dirname(__file__)) + "/config/test.ini"
        self.config.write()

    # 创建一个新配置文件
    def create_new_config(self):
        config = ConfigObj()

        config.filename = os.path.dirname(os.path.dirname(__file__)) + "/config/test1.ini"
        config['student'] = {}
        config['student']['name'] = 'Jardon'
        config['student']['age'] = '56'

        config.write()


if __name__ == '__main__':
    t = TestConfig()
    # t.query_config()
    # t.modify_config()
    # t.add_config()
    # t.del_config()
    # t.write_other_file()
    t.create_new_config()
复制代码

 

posted @   贺满  阅读(662)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示