如何在Python中修复“IndexError:list index out of range”?

时间:2018-02-07 20:51:40

标签: python-3.x

我正在尝试编写一个测验程序,用于保存和读取文本文件,将用户详细信息存储在每个用户的唯一文本文件中。每个用户文件都以以下格式保存:

姓名,年龄,(第1行)
用户名(第2行)
密码(第3行)

我正在尝试从文件中读取两行,因此程序可以决定用户是否输入了正确的登录详细信息,从而导致错误“IndexError:list index超出范围”。我知道错误是由于程序没有看到第三行,但我无法理解为什么。

import sys

def signUp ():
 name=input("Please enter your first name and last name. \n- ")
 name = name.lower()
 username=name[0:3]
 age= input("Please input your age. \n- ")
 username = username + age
 password = input("Please input a password. \n- ")
 print ("Your username is "+username+" and your password is " +password)
 userfile = open(name+".txt", "r")
 userfile.write(name+", "+age+"\n") 
 userfile.write(username+"\n")
 userfile.write(password+"\n")
 userfile.close()
 return name, age, username, password


def login():
 logname = input("Please enter your first name and last name. \n- ")
 logname = logname.lower()
 loginFile = open (logname+".txt", "r")
 inputuname = input ("Enter your username. \n- ")
 inputpword = input("Enter your password. \n- ")
 username = loginFile.readlines(1)
 password = loginFile.readlines(2)
 print (username)
 print (password)
 loginFile.close()
 if inputuname == username[1].strip("\n") and inputpword == 
 password[2].strip("\n"):
    print("success") 
    quiz()
 else:
    print("invalid")



def main():
 valid = False
 print ("1. Login")
 print ("2. Create Account")
 print ("3. Exit Program")
 while valid != True:
     choice =input("Enter an Option: ")

    if choice == "1":
        login()
    elif choice == ("2"):
        user = signUp()
    elif choice== ("3"):
        valid = True
    else:
        print("not a valid option")


def quiz():
 score = 0
 topic = input ("Please choose the topic for the quiz. The topics available 
 are: \n- Computer Science \n- History")
 difficulty = input("Please choose the diffilculty. The difficulties 
 available are: \n- Easy \n- Medium \n- Hard")
 questions = open(topic+"questions.txt", "r")

  for i in range(0,4):
    questions = open(topic+" "+difficulty+".txt", "r")
    question = questions.readline(i)
    print(question)
    answers = open (topic+" "+difficulty+" answers.txt", "r")
    answer = answers.readline(i)
    print(answer)
    userAns = input()
    questions.close
    answers.close
    if userAns == answer:
        score = score + 1
  return score

 main()

1 个答案:

答案 0 :(得分:2)

您应该使用with open(....) as name:进行文件操作。

写入文件时,您应使用a附加/ r+进行读取+写入,或w重新创建 - 而不是“r”仅用于读取。< / p>

至于你的login()

def login():
    logname = input("Please enter your first name and last name. \n- ")
    logname = logname.lower()
    inputuname = input("Enter your username. \n- ")
    inputpword = input("Enter your password. \n- ")
    with open(logname + ".txt", "r") as loginFile:
        loginfile.readline()            # skip name + age line
        username = loginFile.readline() # read a single line
        password = loginFile.readline() # read a single line

    print(username)
    print(password)

    if inputuname == username.strip("\n") and inputpword == password.strip("\n"):
        print("success")          
        quiz()
    else:
        print("invalid")

File-Doku:reading-and-writing-files

如果文件不存在,您的代码将崩溃,请参阅How do I check whether a file exists using Python?