简体   繁体   English

Python csv.DictReader 返回 KeyError

[英]Python csv.DictReader returning KeyError

I'm trying to create a script that reads/writes to a csv file depending on user input.我正在尝试创建一个根据用户输入读取/写入 csv 文件的脚本。 Pretty much it simulates a password manager.它几乎模拟了密码管理器。 However, when i tried to view it through the script using csv.DictReader, it returns KeyError.但是,当我尝试使用 csv.DictReader 通过脚本查看它时,它返回 KeyError。

The csv file was created as a blank and the data were inputted through the script itself. csv 文件创建为空白,数据通过脚本本身输入。

import csv

with open('Pass.csv') as csv_file:

    csv_reader = csv.DictReader(csv_file, delimiter=',')
    for lines in csv_reader:
        print(f'{row["application"]} | {row["ID"]} | {row["password"]}')

I've noticed that if i change the我注意到如果我改变

print(f'{row["application"]} | {row["ID"]} | {row["password"]}')

to

print(lines)

it returns the following output:它返回以下 output:

OrderedDict([(None, ['application', 'ID', 'password'])])
OrderedDict([(None, ['asd', 'dsa', 'asd'])])

So my question is why does it return None in the first place which seems to be the issue that caused the KeyError to arise.所以我的问题是为什么它首先返回 None 这似乎是导致 KeyError 出现的问题。

In the link is the csv file i've used to test the DictReader: http://www.filedropper.com/pass_1链接中是我用来测试 DictReader 的 csv 文件: http://www.filedropper.com/pass_1

I ran your exact code and could not reproduce your error.我运行了您的确切代码,但无法重现您的错误。 After inputting two entries, I get:输入两个条目后,我得到:

>>> readPass()
Application | ID | Password
ap1 | id1 | pw1
application | ID | password
ap2 | id2 | pw2

As you can see, the printing is working fine, but you do have a bug in that you are writing new headers with every entry to the CSV file.如您所见,打印工作正常,但您确实有一个错误,即您正在为 CSV 文件的每个条目编写新标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM