python csv to json
2016-03-24 16:52
585 查看
#Python csv to json
demo.csv
##1.simple code
output
##2.an other method
output
##3.reference
python-write-array-values-into-file
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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- mysql load data 导出、导入 csv
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例