Alex_P
Alex_P

Reputation: 2952

Why is csv.Dictreader reading only the first row/column?

I want to read a csv file into my Tkinter application and split the content of the file in different widgets. I am able to read and enter the text of the first column into the correct entry widget but it fails to continue. I receive a 'KeyError:' exception.

My example code which is just an isolated block to see whether I can print the file content:

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"]

The error message is:

Bible
Traceback (most recent call last):
File "C:/Users/", line 23, in <module>
y = row['author']
KeyError: 'author'

The CSV content is just this:

title, author, year, others, note
Bible,Many,0,Religion,This is the bible.

Can somebody please explain why it only takes the first 'row' and does not continue?

Thank you very much for your insides!

Upvotes: 0

Views: 1921

Answers (2)

Kodiologist
Kodiologist

Reputation: 3495

The error KeyError: 'author' means that the key "author" isn't present in row. Sure enough, if we add print(row), we see:

OrderedDict([('title', 'Bible'), (' author', 'Many'), (' year', '0'), (' others', 'Religion'), (' note', 'This is the bible.')])

So the key is actually " author" rather than "author". Patrick Haugh provides a workaround for this in his answer.

Upvotes: 1

Patrick Haugh
Patrick Haugh

Reputation: 61014

The headers are being read with their intial spaces, so the key is " author" instead of "author". You can set the skipinitialspace formatting parameter to True to prevent this

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"]

Upvotes: 3

Related Questions