[英]Why does this error occur when my text files have clearly more than 1 lines?
I'm a beginner in Python.我是 Python 的初学者。 I've checked my text files, and definitely have more than 1 lines, so I don't understand why it gave me the error on
我检查了我的文本文件,肯定有超过 1 行,所以我不明白为什么它给了我错误
---> 11 Coachid.append(split[1].rstrip())
IndexError: list index out of range
If you want to loop over lines of a file, you have to use如果要遍历文件的行,则必须使用
for line in f.readlines()
...
The problem are the lines:问题在于以下几行:
split=line.split(",")
Coachname.append(split[0].rstrip())
Coachid.append(split[1].rstrip())
The first line assumes that line
contains at lest one comma so that after method split
is called variable split
will be a list of at least length two.第一行假设该
line
至少包含一个逗号,因此在调用方法split
之后,变量split
将是一个至少长度为 2 的列表。 But if line
contains no commas, then split
will have length 1 and Coachid.append(split[1].rstrip())
will generate the error you are getting.但是如果
line
不包含逗号,则split
的长度为 1 并且Coachid.append(split[1].rstrip())
将生成您遇到的错误。 You need to add some conditional tests of the length of split
.您需要添加一些
split
长度的条件测试。
Update更新
Your code should look like (assuming that the correct action is to append an empty string to the Coachid
list if it is missing from the input):您的代码应如下所示(假设正确的操作是 append 如果输入中缺少
Coachid
列表的空字符串):
split=line.split(",")
split_length = len(split)
Coachname.append(split[0].rstrip())
# append '' if split_length is less than 2:
Coachid.append('' if split_length < 2 else split[1].rstrip())
etc. for the other fields
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.