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

标签 python json csv

我是编程新手,过去 3/4 周一直在学习 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"}

谁能帮我解决这个问题?

最佳答案

处理整行后转储。


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)

关于python - 如何在 python 中将 csv 转换为 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38170071/

相关文章:

python - 尝试获取字段值时出现属性错误

Python - 从嵌套 json 中提取数据时出现问题

javascript - 使用js从本地加载CSV文件: no error but no view

Python request.get() 返回 404 页面未找到

python - 如何在Python中命名图形

python - pytest 的 ModuleNotFoundError 问题

json - 查询复杂 CosmosDB 文档的简洁方法

javascript - 使用基于 Div 的 JSON 值之一的 JS 选择框隐藏 div

javascript - 使用 JS 生成 CSV 添加额外的空列

csv - 将 csv 导入 elasticsearch