如何在 python 中将 csv 转换为 json?

新手上路,请多包涵

我对编程很陌生,过去 34 周一直在学习 python,这是给定的作业之一。

输入

A, B, C, D
1, 2, 3, 4
5, 6, 7, 8

输出

{{A:"1", B:"2", C:"3", D:"4"}, {A:"5", B:"6", C:"7", D:"8"}}

我一直在尝试使用以下代码:

 import csv
import 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"}

谁可以帮我这个事?

原文由 naren 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 584
2 个回答

处理整行后转储。


 import csv
import 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)

原文由 falsetru 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于那些喜欢单线的人:

 import csv
import json

json_data = [json.dumps(d) for d in csv.DictReader(open('file.csv'))]

检查这个小提琴的工作示例: https ://pyfiddle.io/fiddle/5992b8f4-552f-4970-91b6-a52cdee16ebc/?i=true

原文由 Antony Fuentes 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题