【问题标题】:cannot figure this out: Key error in DictReader CSV无法弄清楚:DictReader CSV 中的关键错误
【发布时间】:2020-10-20 02:05:44
【问题描述】:

我正在学习 python 3 并且不知道我做错了什么,我所做的所有研究都表明它是正确的。然而,我得到一个关键错误

import csv

with open("csvtest.csv", encoding='utf-8') as software:
    reader = csv.DictReader(software)
    for riga in reader:
        print(riga['ver'])

这是 csv(只是随机数据):

name, ver, status, users
archie,26, production,325

这是我得到的错误:

KeyError: 'ver'

【问题讨论】:

  • 列名有一个前导空格。试试print(riga[' ver'])
  • 是的,就是这样。

标签: python-3.x csv dictionary


【解决方案1】:

我想通了!我正在查看代码,但它是带有错误的 CSV 文件。感谢 Mike67 也确认了!

吸取的教训,不要在 CSV 文件中的逗号后加空格或在 Key 中添加空格

wrong CSV:   name, ver, status, users
correct CSV: name,ver,status,users

wrong key: print(riga['ver']) ## --with spaces in CSV
right key: print(riga[' ver']) ## --with spaces in CSV (name, ver, status, users)
right key: print(riga['ver']) ## --without spaces in CSV (name,ver,status,users)

间距必须在 CSV 和 KEY 中匹配

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-26
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多