Search code examples
pythoncsvkeyerror

csv.DictReader giving unexpected results


My CSV file:

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

My python script:

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

Which returns:

google.com
instagram.com

But this code:

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

Returns:

KeyError: 'password'

I don't understand the issue, and online resources just show examples, none of them explain this problem. They do talk about KeyErrors, but they don't seem to address how the CSV file contains the key ('password'), but still returns key error.

Am I doing something wrong?


Solution

  • In your csv file, there are spaces between the comma separated values. Remove them and it should work.

    Othewise try this:

    import csv
    
    with open(database_path) as database:
        csv_read = csv.DictReader(database)
    
        for card in csv_read:
            print(card[" password"]) # notice the space!!!