0

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?

2
  • 2
    try with list_reader, not with list_csv Commented Jan 29, 2020 at 15:51
  • I’m voting to close this as off-topic/typo/can’t be reproduced. It’s essentially a typo, a trivial mixup. Commented Jan 29, 2020 at 18:30

3 Answers 3

1

You need to loop the reader

  for row in list_csv:
      entries.append(row["subject"])

You are looping the list_csv by mistake.

Sign up to request clarification or add additional context in comments.

1 Comment

Doh, so obvious now 😂 Thank you
1

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

Comments

1

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.