【发布时间】:2021-10-12 19:50:08
【问题描述】:
我正在尝试通过读取 csv 文件的内容并将其写入新的 json 文件来将 csv 文件转换为 json 文件。我在尝试将 csv 文件的一列转换为字典键时遇到错误。我该如何解决这个错误?
我的代码供参考:
import csv
import json
def jsonformat(infile,outfile):
contents = {}
csvfile = open(infile, 'r')
reader = csvfile.read()
for m in reader:
key = m['Order ID']
contents[key] = m
jsonfile = open(outfile, 'w')
json_contents = json.dumps(contents, indent = 4)
jsonfile.write(json_contents)
csvfile.close()
jsonfile.close()
return json_contents
infile = 'orders.csv'
outfile = 'orders.json'
output = jsonformat(infile,outfile)
print(output)
错误信息: TypeError Traceback(最近一次调用最后一次) 在 28 输出文件 = 'orders.json' 29 ---> 30 输出 = jsonformat(infile,outfile) 31 32 打印(输出)
in jsonformat(infile, outfile) 12 阅读器中的 m 为 13: ---> 14 key = m['订单ID'] 15 内容[键] = m 16
TypeError:字符串索引必须是整数
【问题讨论】: