我想将csv文件读入我的Tkinter应用程序,并将文件的内容拆分到不同的小部件中。我能够阅读第一列的文本并将其输入到正确的条目小部件中,但它无法继续。我收到"密钥错误:"异常。
我的示例代码只是一个孤立的块,以查看我是否可以打印文件内容:
import csv
with open("bible.csv", mode="r") as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
x = row["title"]
y = row["author"]
z = row["year"]
错误消息是:
Bible Traceback (most recent call last): File "C:/Users/", line 23, in <module> y = row['author'] KeyError: 'author'
CSV内容是这样的:
title, author, year, others, note
Bible,Many,0,Religion,This is the bible.
有人可以解释为什么它只占用第一"行"而不继续吗?
非常感谢你的内心!
标头使用其初始空格读取,因此密钥" author"
而不是"author"
。 您可以将skipinitialspace
格式参数设置为True
以防止这种情况
import csv
with open("bible.csv", mode="r") as file:
csv_reader = csv.DictReader(file, skipinitialspace=True)
for row in csv_reader:
x = row["title"]
print(x)
y = row['author']
z = row["year"]
错误KeyError: 'author'
意味着密钥"author"
不存在row
中。果然,如果我们加上print(row)
,我们会看到:
OrderedDict([('title', 'Bible'), (' author', 'Many'), (' year', '0'), (' others', 'Religion'), (' note', 'This is the bible.')])
所以关键实际上是" author"
而不是"author"
。帕特里克·霍(Patrick Haugh(在他的回答中为此提供了一种解决方法。