如何在python中将csv转换为json? [英] How to convert csv to json in python?

查看:122
本文介绍了如何在python中将csv转换为json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程非常陌生,过去3/4星期一直在学习python, 这是给出的作业之一.

I'm very new to programming, have been learning python from past 3/4 weeks and this is one of the assignments given.

输入

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

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

I've been trying with the code as:

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中将csv转换为json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆