Python解析config.ini,完成读写操作

文章介绍了如何在Python中自定义函数以调用其他类的方法,并提供了exec_test函数作为示例。同时,展示了使用configparser模块读取和修改config.ini配置文件的值,包括get_value和write_value方法。

解析config.ini以及更改config.ini的值:

import configparser

class ConfigManager:
    def __init__(self, config_file):
        self.config = configparser.ConfigParser()
        self.config_file = config_file
        
        # 如果配置文件存在,则读取
        self.config.read(self.config_file)
    
    def get(self, section, option, default=None):
        """
        获取指定 section 和 option 的值,如果不存在则返回 default 值。
        """
        try:
            return self.config.get(section, option)
        except (configparser.NoSectionError, configparser.NoOptionError):
            return default
    
    def set(self, section, option, value):
        """
        设置指定 section 和 option 的值。
        如果 section 不存在,会自动创建。
        """
        if not self.config.has_section(section):
            self.config.add_section(section)
        
        self.config.set(section, option, value)
        # 保存配置到文件
        with open(self.config_file, 'w') as configfile:
            self.config.write(configfile)



# 示例用法
config = ConfigManager('config.ini')

# 获取值,默认值为 None
username = config.get('UserSettings', 'username', default='default_user')
print(f'Username: {username}')

# 设置值
config.set('UserSettings', 'username', 'new_user')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值