简体   繁体   English

为什么我的 Python CSV 代码在每一行中都以字符串形式读取?

[英]Why is my Python CSV code reading in each row as a string?

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.我正在处理 Code Academy 课程的衍生项目,并在尝试将 CSV 的每一行中的特定列附加到列表时遇到错误。

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.我需要从我的 CSV 中读取每一行,并将“主题”列的值附加到条目列表中。

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 entry.append(row[“subject”]) 类型错误:字符串索引必须是整数

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.)就我所见,我的文件是一个有效的 CSV,除了附加而不是打印之外,我的代码与课程中的代码没有什么不同(我测试了打印,同样的错误。)

My CSV:我的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?我做错了什么使我的代码读取字符串而不是 csv 行?

You need to loop the reader你需要循环阅读器

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

You are looping the list_csv by mistake.您错误地循环了 list_csv。

as @AlirezaTajadod was saying, you are iterating over a bad object, you have to iterate over list_reader正如@AlirezaTajadod 所说,您正在迭代一个坏对象,您必须迭代list_reader

with open("list.csv") as list_csv:
  list_reader = csv.DictReader(list_csv)
  for row in list_reader:
    entries.append(row["subject"])

Need to use list_reader instead of list_csv .需要使用list_reader而不是list_csv See the following example file, marks.csv .请参阅以下示例文件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 .您可以通过遍历list_reader来遍历 CSV 文件的行。 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']现在要获取主题值,只需执行 print row['subject']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM