python - 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"
}
]
}
解决方案
只是取消缩进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)
否则,您将为每个字段添加一个新行,而实际上您只想每行执行一次,而不是每个字段执行一次。
推荐阅读
- php - 由于之前的空白,PHP Session 无法正常工作
我使用 PHP MySQL 创建了网站,并使用数据库来存储会话。当我在主机 ( www.bluehost.com )上设置我的网站时。我的会话到处都是,某些页面会话将起作用,而对于其他页面,它将使我退出。
我搜索了答案,我碰到了python - 如何使用 groupby 将值附加到列表中?
- javascript - 如何在 JsZip 中下载多个音频填充
- php - Laravel Eloquent:有什么方法可以用动态字段更新数据库?
- c - gcc 根据是否观察到地址来改变输出
- python - DEBUG = False 时不显示媒体文件;让他们展示的先决条件是什么?
- swift - 当数组在 Swift 中并发读取时,如何实现 removeAtIndex 的线程安全?
- javascript - 如何使一段文本中的链接作为实际链接工作?
- tensorflow - ImageDataGenerator 导致图像中出现不必要的颜色变化
- discord.js - 关于反应 discord.js 的消息