IndexError:尝试读取文本文件时列表索引超出范围

问题描述 投票:0回答:2

我正在尝试通过输入(像字典一样)来节省单词和阅读器我的代码:

if path.exists("data/inputs/" + word2 + ".txt"):
    file = open("data/inputs/" + word2 + ".txt", "r")

    for line in file:
        fields = line.split("; ")
        field1 = fields[0]
        answer=[field1]
        if fields[1]!="":
            field1 = fields[1]
            answer = [field1, field2]

错误:

    if fields[1]!="":
IndexError: list index out of range

我尝试使用范围进行此操作,但出现错误“必须是整数或索引”,您能告诉我如何使用这些索引并使它工作吗?

python arrays python-3.x indexing text
2个回答
0
投票

您需要删除多余的空间

fields = line.split(";")

0
投票

这意味着文件的至少一行不包含任何“;”,因此split('; ')的结果仅包含一个元素...因此,调用fields[1]是错误的!

© www.soinside.com 2019 - 2024. All rights reserved.