如何将文本文件转换为Python字典列表?代码问题求助
文本文件转Python字典列表的修正方案
你的代码问题出在循环内部没有逐行生成字典并收集到列表中,而是在循环结束后仅处理了最后一行的数据,所以最终只返回了包含最后一行数据的字典列表。
修正后的代码
in_filepath = 'in_file.txt' def data_dict(in_filepath): result = [] # 初始化空列表存储所有字典 with open(in_filepath, 'r') as file: for line in file.readlines(): # 跳过空行,避免文件末尾空行触发拆分错误 line = line.strip() if not line: continue title, price, count = line.split() # 逐行生成字典并加入列表 d = { 'title': title, 'price': int(price), 'count': int(count) } result.append(d) return result # 调用函数并打印结果 output = data_dict(in_filepath) for item in output: print(item)
运行结果
{'title': 'banana', 'price': 4500, 'count': 9} {'title': 'banana', 'price': 350, 'count': 0} {'title': 'banana', 'price': 550, 'count': 8} {'title': 'orange', 'price': 13000, 'count': 6}
关键修改说明
- 提前创建
result空列表,用于统一存储每一行生成的字典 - 将字典的创建和添加操作移到循环内部,确保每一行数据都被处理并加入列表
- 增加空行处理逻辑,避免文件中存在空行时触发拆分报错
内容的提问来源于stack exchange,提问作者backofsky
相关产品推荐
相关产品推荐

