简体   繁体   English

IndexError:使用csv列出索引超出范围

[英]IndexError: list index out of range with csv

I have CSV file that contains multiple columns when I run this code in the first column, will run fine, but when I run it in another column, will display this error 当我在第一列中运行此代码时,我有包含多个列的CSV文件,可以正常运行,但是当我在另一列中运行时,将显示此错误
IndexError: list index out of range

array_of_ids = []
with open('reactions/by_ids.csv','r',newline='') as f:
  reader = csv.reader(f)

  for row in reader:
    array_of_ids.append(row[2])

so, row[0] works, row[2] does not work!! 因此, row[0] row[2]有效, row[2]无效!

You should take a look at your CSV file in a file editor and ensure that each line contains at least 3 entries. 您应该在文件编辑器中查看CSV文件,并确保每行至少包含3个条目。 A common problem is when your CSV file contains a blank link eg the last line. 常见问题是CSV文件包含空白链接(例如最后一行)时。

You could always add if len(row) == 3: before doing your append, this would then have the effect of skipping over any lines that are not correctly formated, for example: if len(row) == 3:您总是可以添加if len(row) == 3:在执行追加之前,这会跳过所有格式不正确的行,例如:

import csv

array_of_ids = []

with open('reactions/by_ids.csv', 'r', newline='') as f:
    reader = csv.reader(f)

    for row in reader:
        if len(row) == 3:
            array_of_ids.append(row[2])    

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

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