您的位置:首页 > 编程语言 > Python开发

python csv to json

2016-03-24 16:52 585 查看
#Python csv to json

demo.csv

4/5/2015 13:34,Apples,73
4/5/2015 3:41,Cherries,85
4/6/2015 12:46,Pears,14
4/8/2015 8:59,Oranges,52
4/10/2015 2:07,Apples,152
4/10/2015 18:10,Bananas,23
4/10/2015 2:40,Strawberries,98

##1.simple code

import csv
import json
demofile = open('demo.csv')
reader =csv.reader(demofile)
data = list(reader)
print data

output

[['4/5/2015 13:34', 'Apples', '73'], ['4/5/2015 3:41', 'Cherries', '85'], ['4/6/2015 12:46', 'Pears', '14'], ['4/8/2015 8:59', 'Oranges', '52'], ['4/10/2015 2:07', 'Apples', '152'], ['4/10/2015 18:10', 'Bananas', '23'], ['4/10/2015 2:40', 'Strawberries', '98']]

##2.an other method

csvfile = open('demo.csv','r')
jsonfile = open('demo.json','w')
fieldnames = ("date","fruit","price")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')

output

{"date": "4/5/2015 13:34", "price": "73", "fruit": "Apples"}
{"date": "4/5/2015 3:41", "price": "85", "fruit": "Cherries"}
{"date": "4/6/2015 12:46", "price": "14", "fruit": "Pears"}
{"date": "4/8/2015 8:59", "price": "52", "fruit": "Oranges"}
{"date": "4/10/2015 2:07", "price": "152", "fruit": "Apples"}
{"date": "4/10/2015 18:10", "price": "23", "fruit": "Bananas"}
{"date": "4/10/2015 2:40", "price": "98", "fruit": "Strawberries"}

##3.reference

python-write-array-values-into-file
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python csv json