我有下面的代码来遍历我的CSV值。输入数据(Sample.csv
):
name,city
jack,nj
matt,ny
并以JSON格式创建输出。所需输出
[
{"name": "jack","city": "PA"},
{"name": "matt","city": "CA"}
]
代码输出:
[{"name,city": "jack,PA"};{"name,city": "matt,CA"};]
代码示例:
#!/usr/bin/python
import json
import csv
csvfile = open('sample.csv', 'r')
jsonfile = open('sample.csv'.replace('.csv','.json'), 'w')
jsonfile.write('{\n[\n')
fieldnames = csvfile.readline().replace('\n','').split(';')
reader = csv.DictReader(csvfile, fieldnames, delimiter=';')
from collections import OrderedDict
for row in reader:
json.dump(OrderedDict([(f, row[f]) for f in fieldnames]), jsonfile, indent=4)
jsonfile.write(';\n')
jsonfile.write(']\n}')
最终输出未对齐到键值对。你知道吗
我能够实现我所需要的,可能不是最好的解决方案,但肯定是我现在正在寻找的。你知道吗
相关问题 更多 >
编程相关推荐