如何用Python解析INI格式文件并转换为嵌套字典?附代码
用Python解析INI格式文件为嵌套字典
你的目标是将如下格式的文件:
[head1]
text1=resp1
text2=resp2
[head2]
text3=resp3
text4=resp4
text5=resp5
解析为嵌套字典:
dicts = {'head1': {'text1': 'resp1', 'text2': 'resp2'}, 'head2': {'text3': 'resp3', 'text4': 'resp4', 'text5': 'resp5'}}
当然可以实现,下面提供两种可行方案:
方案一:使用内置configparser模块(推荐)
configparser是Python标准库中专门处理INI格式文件的模块,无需额外安装,代码简洁且健壮:
import configparser def parse_ini_to_dict(file_path): config = configparser.ConfigParser() config.read(file_path) # 将config对象转换为嵌套字典 nested_dict = {} for section in config.sections(): nested_dict[section] = dict(config[section]) return nested_dict # 使用示例 if __name__ == "__main__": result = parse_ini_to_dict("your_file.ini") print(result)
运行后输出的结果就是你需要的嵌套字典格式。
方案二:手动解析文件(适合理解原理)
如果你想自己实现解析逻辑,也可以逐行读取文件并构建字典:
def parse_manual(file_path): nested_dict = {} current_section = None with open(file_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() # 跳过空行和注释(如果有的话) if not line or line.startswith(';') or line.startswith('#'): continue # 识别section标题 if line.startswith('[') and line.endswith(']'): current_section = line.strip('[]') nested_dict[current_section] = {} # 处理键值对 elif '=' in line: key, value = line.split('=', 1) key = key.strip() value = value.strip() if current_section is not None: nested_dict[current_section][key] = value return nested_dict # 使用示例 if __name__ == "__main__": result = parse_manual("your_file.ini") print(result)
这个方法会逐行处理文件内容,识别section和键值对,最终生成目标嵌套字典。
内容的提问来源于stack exchange,提问作者rocky
相关产品推荐
相关产品推荐

