在python中将csv文件转换为json格式

时间:2019-03-25 06:11:20

标签: python json python-2.7 csv

我已经编写了一个代码来转换我的csvfile,即“ |”分隔的文件以获取特定的json格式。

CSV文件格式:

comment|address|city|country
crowded|others|others|US
pretty good|others|others|US .... 

由于我是python的新手,因此我也尝试了其他代码。如果有人帮助我改正我正在做的错误,那将是有帮助的。

import csv
import json
from collections import OrderedDict

csv_file = 'test.csv'
json_file = csv_file + '.json'


def main(input_file):
    csv_rows = []
    with open(input_file, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        title = reader.fieldnames
        for row in reader:
            entry = OrderedDict()
            for field in title:
                entry[field] = row[field]
            csv_rows.append(entry)

    with open(json_file, 'w') as f:
        json.dump(csv_rows, f, sort_keys=True, indent=4, ensure_ascii=False)
        f.write('\n')


if __name__ == "__main__":
    main(csv_file)

我想要以下json格式

{ 
 "reviewer": {
    "city": "",
    "country": ""   
    "address": "Orlando, Florida"
  },

但是我得到这样的输出:

[
  {
    "COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"Crowded"|"Others"|"Others"|
  },
  {
    "COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"pretty good"|"Others"|"Others"|
  },

1 个答案:

答案 0 :(得分:1)

您缺少分隔符参数。代替:

reader = csv.DictReader(csvfile)

使用:

reader = csv.DictReader(csvfile, delimiter='|')