首页 > 解决方案 > 尝试将 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))

这看起来是我的循环中数据被覆盖的问题,但经过数小时的研究,我不确定如何解决。任何帮助表示赞赏。

标签: pythonpython-3.x

解决方案


您只得到最后一行的原因是因为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 中所述)仍将覆盖现有数据。


推荐阅读