简体   繁体   English

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

[英]IndexError: list index out of range while trying to read a text file

Im trying to make a word saver and reader from input (something like a dictionary) My code:我试图从输入(类似于字典)中制作一个单词保护程序和阅读器我的代码:

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]

Error:错误:

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

I tried doing this with range, got error "must be an int or index", Can you tell me how to work with these indexes and make it work please?我尝试使用范围执行此操作,出现错误“必须是 int 或索引”,您能告诉我如何使用这些索引并使其正常工作吗?

It means that at least one line of your file does not contain any "; ", so the result of split('; ') contains only one element... so calling fields[1] is an error!这意味着您的文件中至少有一行不包含任何“;”,因此split('; ')的结果只包含一个元素......所以调用fields[1]是错误的!

If you want to test whether you have a second field in the line, you should replace if fields[1] != "" by if len(fields) > 1如果要测试行中是否有第二个字段,则应将if fields[1] != ""替换为if len(fields) > 1

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

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