Python将CSV文件转换为JSON文件时出现TypeError错误如何解决
报错原因
你没有使用csv模块的结构化读取能力,直接调用文件对象的read()方法返回的是整个CSV文件的纯字符串,遍历该字符串时得到的每个m是单个字符,无法用列名'Order ID'作为索引取值,因此触发string indices must be integers报错。
修复后可运行代码
import csv import json def jsonformat(infile,outfile): contents = {} # 使用with上下文管理器操作文件,自动处理关闭逻辑 with open(infile, 'r', encoding='utf-8') as csvfile: # 用csv.DictReader读取,自动把首行列名作为字典键 reader = csv.DictReader(csvfile) for m in reader: key = m['Order ID'] contents[key] = m with open(outfile, 'w', encoding='utf-8') as jsonfile: json_contents = json.dumps(contents, indent = 4, ensure_ascii=False) jsonfile.write(json_contents) return json_contents infile = 'orders.csv' outfile = 'orders.json' output = jsonformat(infile,outfile) print(output)
优化说明
- 核心修复点是将直接读取文件字符串的逻辑替换为
csv.DictReader()读取,该方法会自动将CSV第一行作为列名,每一行返回一个以列名为键的字典,匹配你后续按列名取值的需求 - 新增
encoding='utf-8'参数避免中文乱码问题,ensure_ascii=False参数保证导出的JSON文件里中文正常显示而非Unicode编码 - 改用
with上下文管理器操作文件,无需手动调用close()方法,即使运行中途报错也能正常关闭文件
内容的提问来源于stack exchange,提问作者Geraldo
相关产品推荐
相关产品推荐

