gpt4 book ai didi

python - CSV 导入循环重复次数

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:19 25 4
gpt4 key购买 nike

对于 Python 世界来说相当陌生。我编写了以下脚本来转换 csv 文件并覆盖现有的 JSON 文件,准备上传到 Firebase。问题是,脚本读取每一行 4 次,这很奇怪。我的代码如下,很高兴知道我哪里出错了。

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')

CSV 示例 CSV IMAGE

示例输出

{
"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)

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

关于python - CSV 导入循环重复次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60301904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com