以下是一个满足你需求的 Python 操作配置文件的类,这里使用 configparser 模块操作 INI 格式的配置文件:
```python
import configparser
class ConfigFileHandler:
def __init__(self, file_path='config.ini'):
self.config = configparser.ConfigParser()
self.file_path = file_path
self.config.read(self.file_path, encoding='utf-8')
def read_key_value(self, section, key):
if self.config.has_section(section) and self.config.has_option(section, key):
return self.config.get(section, key)
return None
def write_key_value(self, section, key, value):
if not self.config.has_section(section):
self.config.add_section(section)
self.config.set(section, key, value)
with open(self.file_path, 'w', encoding='utf-8') as configfile:
self.config.write(configfile)
def update_key_value(self, section, key, new_value):
current_value = self.read_key_value(section, key)
if current_value is None or current_value != new_value:
self.write_key_value(section, key, new_value)
```
你可以这样使用这个类:
python
# 创建 ConfigFileHandler 实例
config_handler = ConfigFileHandler()
# 写入键值
config_handler.write_key_value('Database', 'Username', 'root')
# 读取键值
username = config_handler.read_key_value('Database', 'Username')
print(username)
# 更新键值
config_handler.update_key_value('Database', 'Username', 'admin')
updated_username = config_handler.read_key_value('Database', 'Username')
print(updated_username)
代码说明
__init__ 方法:初始化 configparser 对象并尝试读取指定的配置文件。
read_key_value 方法:检查指定的 section 和 key 是否存在,如果存在则返回对应的值,否则返回 None。
write_key_value 方法:如果指定的 section 不存在,则创建该 section,然后设置 key 和 value,最后将配置写入文件。
update_key_value 方法:先读取当前的 key 值,若值不存在或与新值不同,则调用 write_key_value 方法更新配置。
配置文件格式通常采用 INI 格式,其结构以 section 和 option 形式组织数据,如:
ini
[section1]
option1 = value1
option2 = value2
[section2]
option3 = value3
这种格式简单易读,适合小型项目,configparser 模块能直接处理该格式的配置文件。