2015-04-14 18 views
0

去年我有一个Python初学者课程。现在我正试图获得一个csv到json转换器。我搜索了一段时间,并修改了一些我找到的代码,直到输出看起来类似于我想要的。我正在使用Python 3.4.2。Python:csv到json转换器的值到密钥对

@kvorobiev这是我的CSV的摘录,但它会做的案件。第一次转换将工作。第二次后,你会看到标题的顺序会在json文件中改变。

CSV文件看起来像这样

Document;Item;Category 
4;10;C 

我所得到的输出文件,截至目前(应用从kvorobiev变化后):以

[ 
{ 
    "Item": "10", 
    "Category": "C", 
    "Document": "4" 
}; 
] 

JSON字符串我想进入输出文件应该看起来像:

[ 
{ 
    "Document": "4", 
    "Item": "10", 
    "Category": "C" 
}, 
] 

你会注意到标题在wron g订单。

下面是代码:

import json 
import csv 

csvfile = open('file1.csv', 'r') 
jsonfile = open('file1.csv'.replace('.csv','.json'), 'w') 

jsonfile.write('[' + '\n' + ' ') 
fieldnames = csvfile.readline().replace('\n','').split(';') 
num_lines = sum(1 for line in open('file.csv')) -1 

reader = csv.DictReader(csvfile, fieldnames) 
i = 0 
for row in reader: 
    i += 1 
    json.dump(row, jsonfile, indent=4,sort_keys=False) 
    if i < num_lines: 
    jsonfile.write(',') 
    jsonfile.write('\n') 
jsonfile.write(' ' + ']') 

print('Done') 

感谢您的帮助。

+0

你输出JSON是有效的?你可以检查http://jsonlint.com/? –

+0

谢谢Vivek。我不知道json输出是否有效,但这是我需要进一步处理数据。 – user87290

回答

3

更换线

reader = csv.DictReader(csvfile, fieldnames) 

reader = csv.DictReader(csvfile, fieldnames, delimiter=';') 

而且,你打开file1.csv后来从file.csv

num_lines = sum(1 for line in open('file.csv')) -2 

得到线数您的解决方案可减少到

import json 
import csv 
csvfile = open('file1.csv', 'r') 
jsonfile = open('file1.csv'.replace('.csv','.json'), 'w') 
jsonfile.write('{\n[\n') 
fieldnames = csvfile.readline().replace('\n','').split(';') 
reader = csv.DictReader(csvfile, fieldnames, delimiter=';') 
for row in reader: 
    json.dump(row, jsonfile, indent=4) 
    jsonfile.write(';\n') 
jsonfile.write(']\n}') 

如果您想保存从CSV列的顺序,你可以使用

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}') 
+0

谢谢你,你太棒了!彻底解决了我的问题。 – user87290

+0

@ user87290不客气。我很高兴我的解决方案帮助你。 – kvorobiev

+0

@ user87290你能提供你的输入文件吗? – kvorobiev