You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取文件转字典报错求助:附示例数据与代码

问题分析与解决方案

你的代码问题点

  • 列表索引错误:final[i+1, i+2, int(i+3)] 是错误的列表取值方式,Python列表不支持元组索引,需逐个取出元素并处理
  • 数据清洗逻辑混乱:finalx += i.strip(' ') 未初始化finalx,且会把所有字符串拼接在一起,完全破坏原数据结构
  • 一维列表存储所有数据:把所有行的元素塞进一个一维列表,后续按步长4遍历容易出错,不如直接每行处理成子列表

修正后的完整代码

# 读取文件并处理数据
state_data = {}

with open('states.txt', 'r') as f:
    for line in f:
        # 分割每行、过滤空字段(处理末尾逗号)、清洗每个字段的空格
        parts = [part.strip() for part in line.strip().split(',') if part.strip()]
        if len(parts) == 4:
            abbr, name, capital, population = parts
            # 以州缩写为键,嵌套字典存储详细信息
            state_data[abbr] = {
                'state_name': name,
                'capital': capital,
                'population': int(population)
            }

# 导出为JSON文件
import json
with open('states.json', 'w') as json_file:
    json.dump(state_data, json_file, indent=4)

# 导出为CSV文件
import csv
with open('states.csv', 'w', newline='') as csv_file:
    fieldnames = ['state_abbr', 'state_name', 'capital', 'population']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    # 遍历字典写入每行数据
    for abbr, info in state_data.items():
        writer.writerow({
            'state_abbr': abbr,
            'state_name': info['state_name'],
            'capital': info['capital'],
            'population': info['population']
        })

print(state_data)

代码说明

  • 数据读取与清洗:用列表推导式一次性完成分割、去空、去空格操作,确保每行都是4个有效字段
  • 字典构建:以州缩写为键,嵌套字典存储州名、首府、人口,结构清晰且方便后续导出
  • JSON导出:使用json.dump直接写入文件,indent=4让JSON格式更易读
  • CSV导出:用csv.DictWriter定义表头,遍历字典逐行写入,保证CSV结构规范

内容的提问来源于stack exchange,提问作者May

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 12:37:18