我一直在尝试使用python 3将csv文件转换为json。我想转换一个看起来或多或少像这样的csv文件:
Key ,Field_1 ,Field_2 ...
0 ,a ,e ...
1 ,b ,f ...
2 ,c ,g ...
3 ,d ,h ...
放入结构化密钥的json文件:[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文件的末尾。
答案 0 :(得分:1)
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)
答案 1 :(得分:0)
这应该做您想要的。
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')