Search code examples
python-3.xcsvkeyerror

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!


Solution

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