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

被折叠的 条评论
为什么被折叠?



