如何在Python中读取txt文件数据并转换为指定格式的嵌套字典
Python TXT转嵌套字典实现方案
无需修改现有txt文件结构,直接使用以下代码即可得到目标格式的字典:
# 初始化结果字典 pokemon = {} # 读取txt文件,替换为你自己的文件路径 with open("pokemon.txt", "r", encoding="utf-8") as file: for line in file: # 去除首尾空白字符,跳过空行 line = line.strip() if not line: continue # 按逗号拆分字段并去除各字段首尾空格 name, quantity_str, fee_str, powers_str = [i.strip() for i in line.split(",")] # 组装嵌套字典 pokemon[name] = { "quantity": int(quantity_str), "fee": int(fee_str), "powers": powers_str.split() }
执行完成后pokemon变量就是你要求的结构,直接调用即可。
内容的提问来源于stack exchange,提问作者Max Chi
相关产品推荐
相关产品推荐

