2964502
2964502

Reputation: 4479

key error while retrieving csv files into list

How to prevent error when certain column such as 'Country' does not exist in some file?

import csv
files = glob.glob ('..\\*.csv')
for file in files:
    countries = []
    with open ('data.csv', newline='') as infile:
        reader = csv.DictReader(infile)
        for row in reader:
            countries.append(row['Country'])
    print (countries)

Upvotes: 0

Views: 1784

Answers (1)

zero323
zero323

Reputation: 330163

You can check if field exist

if 'Country' in reader.fieldnames:
   ...

Or you can deal with a problem at the row level like you'll with any dictionary like structure. You can use .get method which will return None if key does not exist:

countries.append(row.get('Country'))

Alternatively you can use setdefault method and provide default value (it can be also done with get):

row.setdefault('Country', 'Unknown')

or even wrap your code in a try-catch block:

try:
    countries.append(row['Country'])
except KeyError:
    pass

Combining this with list comprehensions:

if 'Country' in reader.fieldnames:
    countries = [row.get('Country') for row in reader]

Upvotes: 1

Related Questions