csv.DictReader给出意想不到的结果

时间:2018-01-27 17:30:46

标签: python csv keyerror

我的CSV文件:

website, username, password
google.com, test1, lamepass
instagram.com, test2, passlame

我的python脚本:

with open(database_path) as database:
    csv_read = csv.DictReader(database)
    for card in csv_read:
        print(card['website'])

返回:

google.com
instagram.com

但是这段代码:

with open(database_path) as database:
    csv_read = csv.DictReader(database)
    for card in csv_read:
        print(card['password'])

返回:

KeyError: 'password'

我不了解这个问题,在线资源只是展示了一些例子,没有一个能解释这个问题。他们确实在讨论KeyError,但他们似乎并未解决CSV文件包含密钥('password')的方式,但仍会返回密钥错误。

我做错了吗?

2 个答案:

答案 0 :(得分:3)

在csv文件中,逗号分隔值之间有空格。删除它们,它应该工作。

其他尝试:

import csv

with open(database_path) as database:
    csv_read = csv.DictReader(database)

    for card in csv_read:
        print(card[" password"]) # notice the space!!!

答案 1 :(得分:0)

password(和username)之前还有一个额外的空格:

csv = """website, username, password
google.com, test1, lamepass
instagram.com, test2, passlame"""

with open('file.csv', 'w+') as f:
    f.write(csv)

import csv

with open('file.csv', 'r+') as database:
    csv_read = csv.DictReader(database)
    for card in csv_read:
        print(card)


OrderedDict([('website', 'google.com'), (' username', ' test1'), (' password', ' lamepass')])
OrderedDict([('website', 'instagram.com'), (' username', ' test2'), (' password', ' passlame')])

您应该尝试使用以下命令从csv中删除多余的空格:

csv = csv.replace(", ", ",")