【发布时间】:2019-03-06 00:52:42
【问题描述】:
我有一个包含大约一千行的 csv 文件,如下所示:
id,name,email,date_of_birth,arrive_time
4657,name1,email1,01/10/1987,15:50
7594,name2,email2,02/10/1987,10:05
我需要在json数组视图中转换:
[
{
"name": "name1",
"date_of_birth": "01/10/1987"
},
{
"name": "name2",
"date_of_birth": "02/10/1987"
}
]
我用过的代码:
import csv
import json
file = 'myCsvFile.csv'
json_file = 'myLsonFile.json'
def read_CSV(file, json_file):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
field = reader.fieldnames
for row in reader:
csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
def convert_write_json(data, json_file):
with open(json_file, "w") as f:
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': ')))
f.write(json.dumps(data))
read_CSV(file,json_file)
这段代码的输出是
{
"name": "id;name;email;date_of_birth;arrange_time",
"date_of_birth": null
}
{
"name": "4657;name1;email1;01/10/1987;15:50",
"date_of_birth": null
}
但我不知道如何从 csv 中选择某些列并创建一个数组。
【问题讨论】:
标签: python json pandas csv jupyter-notebook