使用 python 将 CSV 文件转换为 JSON 文件

Converting a CSV file into a JSON file using python

我一直在尝试使用 python 将 csv 文件转换为 json 3. 我想转换一个 csv 文件,它看起来或多或少像这样:

Key ,Field_1 ,Field_2 ...
0   ,a       ,e       ...
1   ,b       ,f       ...
2   ,c       ,g       ...
3   ,d       ,h       ...

进入 json 结构化文件 Key : [Field_1, Field_2, ...]

这样上面的 csv 最终看起来像

{
  "0" : ["a", "e", ...]
  "1" : ["b", "f", ...]
  "2" : ["c", "g", ...]
  "3" : ["d", "h", ...]
}

我一直在尝试使用下面的代码,但无法填补缺失的部分,例如将每个值分配给 json 文件中的相应部分。

csv = pd.read_csv("file.csv")
n = 0
length = # number of keys
for i in csv:
    if n == 0:
        for y in range(lentgh):
            # Assign as the header
    else:
        for y in range(length):
            # Assign as the properties
    n += 1

我也在努力使所有新数据自动附加到 json 文件的末尾。

json 仍会缩进值列表,但这会将您的 csv 转换为您想要的字典并将其附加到 json 文件

import csv
import json

with open('blah.csv') as f:
    reader = csv.reader(f)
    next(reader)
    d = dict((rows[0], rows[1:]) for rows in reader)

with open('blah.json', 'a') as f:
    json.dump(d, f, indent=4)

这应该可以满足您的要求。

import csv
import json

csvfile = open('C:\your_path\file.csv', 'r')
jsonfile = open('C:\your_path\file.json', 'w')

fieldnames = ("ID","Name","Address","State")
reader = csv.DictReader(csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')