首页 > 解决方案 > 在python中将csv文件转换为json格式

问题描述

我已经编写了一个代码来转换我的 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"|
  },

标签: pythonjsonpython-2.7csv

解决方案


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

reader = csv.DictReader(csvfile)

利用:

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

推荐阅读