如何根据字典值对带#注释的配置文件进行定制?
配置文件定制功能实现方案
需求说明
我有一个配置文件,部分行以#注释,原始内容如下:
#year=1889 #model=foo #size=small working=y
需基于一个字典变量对配置文件执行以下操作:
- 配置中已存在的项,若原先是注释状态则取消注释,并根据字典值调整内容
- 已匹配且值一致的项保持不变
- 字典中新增的配置项不添加到文件中
对应的字典示例:
mydict = { "model":"bar", # 取消注释并修改值 "size":"small", # 仅取消注释 "working":"y", # 保持原样 "newValue":"new" # 不添加到文件 }
编辑后的预期配置文件:
#year=1889 model=bar size=small working=y
Python实现代码
def update_config_file(config_path, update_dict): # 读取原配置文件所有行 with open(config_path, 'r') as f: lines = f.readlines() updated_lines = [] for line in lines: stripped_line = line.strip() # 处理带注释的配置行 if stripped_line.startswith('#'): candidate_line = stripped_line[1:].lstrip() if '=' in candidate_line: key, _ = candidate_line.split('=', 1) key = key.strip() if key in update_dict: # 替换为字典中的值,取消注释 updated_lines.append(f"{key}={update_dict[key]}\n") continue # 处理非注释的配置行 elif '=' in stripped_line: key, current_val = stripped_line.split('=', 1) key = key.strip() current_val = current_val.strip() if key in update_dict: if current_val != update_dict[key]: # 值不同时更新内容 updated_lines.append(f"{key}={update_dict[key]}\n") continue # 不需要修改的行直接保留 updated_lines.append(line) # 将修改后的内容写回文件 with open(config_path, 'w') as f: f.writelines(updated_lines) # 示例调用 if __name__ == "__main__": mydict = { "model":"bar", "size":"small", "working":"y", "newValue":"new" } update_config_file('config.ini', mydict)
代码逻辑说明
- 读取文件:一次性读取配置文件所有行,方便逐行处理
- 逐行处理:
- 对于注释行,去掉
#后检查是否为有效配置项,若键在字典中则替换为字典值并取消注释 - 对于非注释的配置行,提取键和当前值,若键在字典中且值不同则更新内容
- 不符合上述情况的行(如未匹配的注释行、无关行)直接保留原内容
- 对于注释行,去掉
- 写入文件:将处理后的所有行写回原配置文件,完成更新
内容的提问来源于stack exchange,提问作者schande
相关产品推荐
相关产品推荐

