代码运行触发IndexError: list index out of range故障排查求助
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.txtcontains 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
bcryptto hash passwords before storing them. - Add error handling for cases where
AccountFile.txtdoesn’t exist (wrap the file open in atry-except FileNotFoundErrorblock).
内容的提问来源于stack exchange,提问作者Joshua Smith

