Reputation: 83
I'm trying to retrieve values from multiple csv files that are located in a directory. When performing if row['opponent-points-per-game-rank'] == 6:
I am getting a Key Error. When I do something like:
if 'opponent-points-per-game-rank' in myfilereader.fieldnames:
testrank = [row.get('opponent-points-per-game-rank') for row in myfilereader]
It will find the column name. Any reason why it can find the column name this way but not the other? Here is the link to my csv file. My code right now:
import os
import csv
testrank = []
directory = os.path.join("c:\\","Users\sm\OneDrive\TestProject")
for root,dirs,files in os.walk(directory):
for file in files:
if file.endswith(".csv"):
f=open(file, 'r')
myfilereader = csv.DictReader(f)
for row in myfilereader:
if row['opponent-points-per-game-rank'] == 6:
testrank.append(row['Team'])
f.close()
print(testrank)
Upvotes: 1
Views: 753
Reputation: 561
I figure that row
is an OrderedDict object. Here is my solution. Notice that you need to cast v
to int because it is str.
import os
import csv
testrank = []
directory = os.path.join("c:\\","Users\sm\OneDrive\TestProject")
for root,dirs,files in os.walk(directory):
for file in files:
if file.endswith(".csv"):
f=open(file, 'r')
myfilereader = csv.DictReader(f)
for row in myfilereader:
for k,v in row.items():
if k == 'opponent-points-per-game-rank' and int(v) == 6:
testrank.append(row['Team'])
f.close()
print(testrank)
Upvotes: 2
Reputation: 7863
I tried to reproduce this issue using the file you linked, but I am not getting any errors. However, the value of row['opponent-points-per-game-rank']
is a string, so row['opponent-points-per-game-rank'] == 6
always evaluates to False
. When this condition is replaced by int(row['opponent-points-per-game-rank']) == 6
everything seems to work fine.
Upvotes: 2