gpt4 book ai didi

python - CSV - 列表索引超出范围

转载 作者:太空狗 更新时间:2023-10-30 01:44:58 25 4
gpt4 key购买 nike

读取 CSV 文件时出现此错误(无标题、3 列、第二和第三个字符串):

Traceback (most recent call last):
File "C:\Python32\fantasy.py", line 72, in module>
some=row[1]
IndexError: list index out of range*

下面是部分代码。坚持下去是非常简单的事情,但我对它如何不起作用一无所知。我是编码新手,但之前处理过 csv 模块,这部分从来没有遇到过问题,只是在记事本中制作了一些测试 csv 文件,看看它是否会从相同的代码中读取,确实如此。我不知道。

import csv
##############some other code, working good and I believe not relevant to this problem
file=open(r"C:\Users\me\Desktop\file-2.csv","r")
reader=csv.reader(file, delimiter=',', quotechar='"')

for row in reader:
some=row[1]

最佳答案

尝试检查空行。另外,避免使用 file 作为变量名。 "r" 是打开的默认模式。

import csv

with open(r"C:\Users\me\Desktop\file-2.csv") as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
for row in reader:
if row:
some=row[1]

关于python - CSV - 列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13039392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com