将csv(;)转换为Json文件

问题描述 投票:1回答:1

我尝试将CS​​V文件(;分隔)转换为JSON文件我的CSV文件结构类似于以下示例:ID; NAME; AGE; CLASS; SEC1; ram; 13; 8; B

像那样

import csv,json
csvf_path='xyz'
jsonf_path='mnb'
Data={}
with csv(csvf_path) as csvFile:
    csvRider=csv.DictReader(csvFile)
    for csvRow as csvRider:
        ID=csvRow('ID')
        data[Id]=csvRow

with open(jsonf_path,'W') as jsonFile
    jsonFile.write(json.dumps(data,indent=4))

-> data [Id] = csvRow ---->错误----> KEyerror我也尝试使用

csv.reader(csvf_path,delimiter=';')

然后再次出现错误,

TypeError:列表索引必须是整数或切片,而不是str。->

ID=ID=csvRow('ID')

json python-3.x csv data-conversion
1个回答
1
投票

提供的代码中的缩进是错误的。看看这部分:

csvRider=csv.DictReader(csvFile)
    for csvRow as csvRider:
    ID=csvRow('ID')
    data[Id]=csvRow

for应该缩进。


也就是说,使用类似的方法将CSV(;)转换为JSON
import csv
import json

with open('data.csv') as f:
    reader = csv.DictReader(f, delimiter=';')
    rows = list(reader)

with open('result.json', 'w') as f:
    json.dump(rows, f)

结果:

[
    {
        "ID": "1",
        "NAME": "ram",
        "AGE": "13",
        "CLASS": "8",
        "SEC": "1"
    }
]

© www.soinside.com 2019 - 2024. All rights reserved.