You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

代码运行触发IndexError: list index out of range故障排查求助

Fixing the IndexError: list index out of range in Your Login System

Hey Joshua, let's break down why your login code suddenly started throwing this error—this is a common gotcha with file-based account systems, so we’ll get it sorted quickly.

What’s Causing the Error?

The IndexError: list index out of range here means when your code tries to access login_info[0] or login_info[1], the login_info list has fewer than 2 elements. This almost always happens for one of these reasons:

  • Your AccountFile.txt contains blank lines (or lines with only whitespace) that split into empty lists.
  • During registration, the code wrote incomplete entries (e.g., only a username, no password) to the file.
  • The delimiter you use to split username/password doesn’t match what was saved during registration.

Step 1: Check Your Account File First

Open AccountFile.txt and look for:

  • Empty lines (delete any you find)
  • Lines that don’t have both a username and password separated by a consistent character (like a comma or colon)

Step 2: Fix the Registration Code

Your current Register function is missing consistent formatting for account entries. Let’s update it to ensure every line has a valid username + password pair:

def Register():
    username = input("Please input the first 3 or 4 letters of your first name and your year: ")
    password = validate()  # Assuming validate() returns a valid user password
    # Format entry with a comma delimiter and add a newline
    account_entry = f"{username},{password}\n"
    # Use 'with' to safely handle file opening/closing
    with open("AccountFile.txt", "a") as file:
        file.write(account_entry)

Using with is safer than raw open() because it automatically closes the file even if an error occurs.

Step 3: Update the Login Code to Handle Edge Cases

Modify your Login function to skip blank lines and verify the split line has both elements before checking credentials:

def Login():
    username = input("Enter your username: ")
    password = input("Enter your password: ")
    
    with open("AccountFile.txt", "r") as file:
        for line in file:
            # Remove whitespace and newlines from the line
            cleaned_line = line.strip()
            # Skip empty lines entirely
            if not cleaned_line:
                continue
            # Split using the same delimiter as registration (comma here)
            login_info = cleaned_line.split(",")
            # Only check credentials if we have exactly 2 elements
            if len(login_info) == 2:
                if login_info[0] == username and login_info[1] == password:
                    print("Login successful!")
                    return
        # If we exit the loop without returning, credentials are invalid
        print("Invalid username or password.")

Quick Best Practice Note

  • Never store passwords in plain text! This works for a learning project, but in real applications, use a library like bcrypt to hash passwords before storing them.
  • Add error handling for cases where AccountFile.txt doesn’t exist (wrap the file open in a try-except FileNotFoundError block).

内容的提问来源于stack exchange,提问作者Joshua Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:31:04