如何在python中将csv转换为json?
我对编程非常陌生,过去3/4星期一直在学习python,这是给出的作业之一。
输入项
A, B, C, D1, 2, 3, 4
5, 6, 7, 8
输出量
{{A:"1", B:"2", C:"3", D:"4"}, {A:"5", B:"6", C:"7", D:"8"}}
我一直在尝试代码为:
import csvimport json
csvfile = open('test.csv','r')
jsonfile = open('test.json','w')
x = ("a","b","c","d")
reader = csv.DictReader(csvfile, x)
for row in reader:
json.dump(row, jsonfile)
此代码的输出如下:
{"a": "1", "null": ["5", "6", "7", "8", "9"], "c": "3", "b": "2", "d": "4"}
谁可以帮我这个事?
回答:
处理完整行后转储。
import csvimport json
with open('test.csv') as f:
reader = csv.DictReader(f)
rows = list(reader)
with open('test.json', 'w') as f:
json.dump(rows, f)
以上是 如何在python中将csv转换为json? 的全部内容, 来源链接: utcz.com/qa/424153.html