【发布时间】:2022-01-04 23:28:03
【问题描述】:
我已经编写了一个 python 代码来将 csv 文件转换为 json 文件。但输出与我想要的不一样。请查看并提出修改建议。
下面是预期的 json 文件。
[
{
"id": "1",
"MobileNo": "923002546363"
},
{
"id": "2",
"MobileNo": "923343676143"
}
]
下面是我用python写的代码。
import csv, json
def csv_to_json(csvFilePath, jsonFilePath):
jsonArray = []
#read csv file
with open(csvFilePath, encoding='utf-8') as csvf:
#load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csvf)
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
jsonArray.append(row)
#convert python jsonArray to JSON String and write to file
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
csvFilePath = r'my_csv_data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)
【问题讨论】:
-
当前输出是多少?
-
你实际得到了什么输出?旁注:您可以减少对
json.dumps()的调用,然后将jsonf.write()减少为单个json.dump(jsonf, jsonArray)。