首页 > 解决方案 > CSV import looping duplicate times

问题描述

Rather new to the Python world. I wrote the following script to convert my csv file and overwrite the existing JSON file, ready to upload to Firebase. Problem is, the script is reading each row 4 times which is odd. My code is below, would be great to know where I'm going wrong.

import csv
import json
from collections import OrderedDict

fieldnames = ("Code", "Currency", "Rate", "Last Updated")
entries = []

with open('rates.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames)
    for row in reader:
        entry = OrderedDict()
        for field in fieldnames:
            entry[field] = row[field]
            entries.append(entry)

output = {
    "rates": entries
    }

with open('rates2.json', 'w') as jsonfile:
    json.dump(output, jsonfile, indent=2, ensure_ascii=False)
    jsonfile.write('\n')

Example of the CSV CSV IMAGE

Example Output

{
  "rates": [
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AED ",
      "Currency": " UAE Dirham",
      "Rate": "4.2499",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    },
    {
      "Code": "AUD ",
      "Currency": " Australian Dollar",
      "Rate": "1.8299",
      "Last Updated": "18/02/2020 10:13"
    }
  ]
}



标签: pythoncsv

解决方案


只是取消缩进entries.append(...)

with open('rates.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames)
    for row in reader:
        entry = OrderedDict()
        for field in fieldnames:
            entry[field] = row[field]
        entries.append(entry)

否则,您将为每个字段添加一个新行,而实际上您只想每行执行一次,而不是每个字段执行一次。


推荐阅读