python - 尝试将 CSV 加载到 JSON 格式。似乎只在 JSON 中指定了 CSV 的最后一行
问题描述
我正在尝试编写一个 python 脚本来从 CSV 中获取数据并将其格式化为特定嵌套格式的 JSON。我似乎只得到了 CSV 指定的最后一行。请在下面找到我的代码:
import csv, json, itertools
from collections import defaultdict
csvFilePath = "example.csv"
jsonFilePath = "example.json"
startCSV= 1
finishCSV= 10
# Read the CSV and add data to a dictionary
data = defaultdict()
with open(csvFilePath) as csvFile:
tmp = {}
csvReader = csv.DictReader(csvFile)
for csvRow in itertools.islice(csv.DictReader(csvFile), begin, end):
tmp['email'] = csvRow['email']
del csvRow['email']
tmp['dataFields'] = csvRow
data.update(tmp)
tmp = {}
#Write the data to a JSON file
with open(jsonFilePath, "w") as jsonFile:
jsonFile.write(json.dumps(data, indent=4, ensure_ascii=False))
这看起来是我的循环中数据被覆盖的问题,但经过数小时的研究,我不确定如何解决。任何帮助表示赞赏。
解决方案
您只得到最后一行的原因是因为csvRow
迭代到 csv 文件中的最后一行,然后将自身添加到data
.
要解决此问题,只需将循环体缩进如下:
with open(csvFilePath) as csvFile:
tmp = {}
csvReader = csv.DictReader(csvFile)
for csvRow in itertools.islice(csv.DictReader(csvFile), startCSV, finishCSV):
tmp['email'] = csvRow['email']
del csvRow['email']
tmp['dataFields'] = csvRow
data.update(tmp)
tmp = {}
除此之外,请确保电子邮件在 csv 文件中是唯一的。根据dictionary.update()
文档,重复的电子邮件地址将替换data
. 要解决此问题,请替换update()
为append()
调用,并data
按照 Brennen 的解决方案中所述创建一个数组。
with open(csvFilePath) as csvFile:
# with `data = []`
tmp = {}
csvReader = csv.DictReader(csvFile)
for csvRow in itertools.islice(csv.DictReader(csvFile), startCSV, finishCSV):
tmp['email'] = csvRow['email']
del csvRow['email']
tmp['dataFields'] = csvRow
data.append(tmp) # CHANGED: You used update here.
tmp = {}
编辑:如果您在 csv 中的电子邮件地址不是唯一的,那么将它们用作键(如 Brennan 的Minimal Solution with Email as the Key 中所述)仍将覆盖现有数据。
推荐阅读
- swift - 苹果手表系列 4 中应用工作的跌倒检测功能
- angular - 如何在数组 angular 7 中使用 groupby 显示有组织的类别?
- python - 如何在Python中匹配两个csv文件之间的数据
- android - 如何在 AutoCompleteTextView 中的项目单击侦听器上从 json 获取 id?
- javascript - 当我在 on 事件期间将数据发送到函数时,jquery 中的 on 事件是否正常,那我该如何解决?
- django - 注册后的表格没有提交Django
- php - 查询始终成功?
- arrays - 如何将元素添加到空数组
- python - Python Selenium 获取具有相同文本的所有链接的列表
- javascript - 超过最大调用堆栈大小 JS