简体   繁体   English

如何在Python中修复“ IndexError:列表索引超出范围”?

[英]How to fix “IndexError: list index out of range” in Python?

I am trying to write a quiz program that saves and reads from text files, storing the users details in a unique text file for each user. 我正在尝试编写一个保存和读取文本文件的测验程序,将用户详细信息存储在每个用户的唯一文本文件中。 Each user file is saved in the format: 每个用户文件均以以下格式保存:

name, age, (line 1) 名称,年龄(第1行)
username (line 2) 用户名(第2行)
password (line 3) 密码(第3行)

I currently am getting the error 'IndexError: list index out of range' whilst attempting to read a two lines from a file so the program can decide whether the user has entered the correct login details. 我目前在尝试从文件中读取两行时收到错误“ IndexError:列表索引超出范围”,以便程序可以确定用户是否输入了正确的登录详细信息。 I understand that the error is due to the program not seeing line three but I cannot understand why. 我知道错误是由于程序看不到第三行,但我不明白为什么。

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()

You should use with open(....) as name: for file operations. 您应该使用with open(....) as name:用于文件操作。

When writing to a file you should use a for append / r+ for read+write, or w to recreate it - not 'r' that is for reading only. 写入文件时,您应该使用a来附加/ r+来进行读写操作,或者使用w来重新创建它-而不是仅用于读取的'r'。

As for your login() : 至于您的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 File-Doku: 读取和写入文件

If the file does not exist your code will crash, see How do I check whether a file exists using Python? 如果该文件不存在,您的代码将崩溃,请参阅如何使用Python检查文件是否存在?

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

相关问题 如何在Python中修复“ IndexError:列表索引超出范围” - How to fix “IndexError: list index out of range” in python 如何解决“ IndexError:列表索引超出范围” - How to fix “IndexError: list index out of range” 如何解决“ IndexError:列表索引超出范围”? - How to fix “IndexError: list index out of range”? 如何修复'IndexError:列表索引超出范围'错误 - How to fix 'IndexError: list index out of range' error 如何修复IndexError:在抓取时列出索引超出范围 - How to fix IndexError: list index out of range while scraping 如何修复 IndexError:字符串索引超出范围 - Python - How to fix IndexError: String index out of range - Python IndexError:列表分配索引超出范围Python 3这是什么意思,我该如何解决? - IndexError: list assignment index out of range Python 3 What does this mean and how do I fix it? 如何修复Python上p2p聊天应用程序的“ IndexError:列表索引超出范围”错误? - How to fix “IndexError: list index out of range” error of p2p chat application on Python? 如何解决“ IndexError:图像索引超出范围”? - How to fix “IndexError: image index out of range”? IndexError:在for循环python中列出超出范围的索引 - IndexError: list index out of range in for loop python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM