Reputation: 155
I'm working on a spin-off project from a Code Academy lesson and running into an error when trying to append a specific column from each row of a CSV to a list.
The code from the lesson:
import csv
with open('cool_csv.csv') as cool_csv_file:
cool_csv_dict = csv.DictReader(cool_csv_file)
for row in cool_csv_dict:
print(row['Cool Fact'])
I need to read in each row from my CSV, and append the value of the "subject" column to the entries list.
import csv
entries = []
with open("list.csv") as list_csv:
list_reader = csv.DictReader(list_csv)
for row in list_csv:
entries.append(row["subject"])
But I'm getting the following error:
entries.append(row[“subject”]) TypeError: string indices must be integers
I get that the error is saying that the value passed by row was a string, so I can’t access it with the header name, but what I don’t get is why. My file is a valid CSV as far as I can see, and my code is no different to that in the lesson other than appending instead of printing (I tested print, same error.)
My CSV:
subject,subject_type
first,test
second,test
What have I done wrong that’s making my code read in a string instead of the csv row?
Upvotes: 0
Views: 526
Reputation: 38502
Need to use list_reader
instead of list_csv
. See the following example file, marks.csv.
id,subject,marks
1,English,20
2,French,21
3,Spanish,21
So we have,
import csv
list_reader = csv.DictReader(open("marks.csv"))
You may iterate over the rows of the CSV file by iterating over list_reader
. So if we do a for loop like below
for row in list_reader:
print row
It will print row like this,
{'id': '1', 'subject': 'English','marks': '20' }
{'id': '2', 'subject': 'French', 'marks': '21' }
{'id': '3', 'subject': 'Spanish','marks': '22' }
Now to get the subject value simply do print row['subject']
Upvotes: 1
Reputation: 17322
as @AlirezaTajadod was saying, you are iterating over a bad object, you have to iterate over list_reader
with open("list.csv") as list_csv:
list_reader = csv.DictReader(list_csv)
for row in list_reader:
entries.append(row["subject"])
Upvotes: 1
Reputation: 327
You need to loop the reader
for row in list_csv:
entries.append(row["subject"])
You are looping the list_csv by mistake.
Upvotes: 1