如何在Python中实现TXT文件的用户名与密码关联验证
Hey there, let's get this login problem sorted out for you. The core issue with your current code is that it only checks if the username exists somewhere in the file and if the password exists somewhere else in the file—but it never verifies that the password actually belongs to the username you entered. That's why entering Undertaker with Triple H's password works right now; the code just sees the password exists in the file, not which user it's tied to.
Let's break down what's wrong with the original code:
- When checking the username, you're just verifying it appears in any line of the file (which works for existence, but not for linking to a password).
- For the password, you're doing the same loose check—any password present in the file will pass, regardless of which user it belongs to.
Here's the fixed code that links usernames to their correct passwords:
print("Consultar Gastos") while True: # Use 'with' to safely open and close the file (better practice) with open("Moradores.txt", "r", encoding="utf-8") as file: all_users = file.readlines() mLogin = input("Login: ") user_found = False correct_password = "" # First, find the user's entry and grab their password for line in all_users: # Clean up the line and split into user details cleaned_line = line.strip() if not cleaned_line: continue # Skip empty lines user_info = cleaned_line.split("|") # Assuming each line follows: Username|Email|Password if len(user_info) >= 3 and user_info[0].strip() == mLogin.strip(): user_found = True correct_password = user_info[2].strip() break # Handle unregistered username if not user_found: while True: print("Name not registered, try again") mLogin = input("Login: ") # Re-check for the new username for line in all_users: cleaned_line = line.strip() if not cleaned_line: continue user_info = cleaned_line.split("|") if len(user_info) >=3 and user_info[0].strip() == mLogin.strip(): user_found = True correct_password = user_info[2].strip() break if user_found: break # Now verify the password matches the user's actual password mPass = input("Password: ") while mPass.strip() != correct_password: print("Wrong Password, try again") mPass = input("Password: ") # Successful login print(f"Welcome back, {mLogin}!") break # Exit the loop after valid login
Key improvements made:
- Link username to password: We loop through each line to find the exact entry matching your input username, then extract only that user's password for comparison.
- Clean input and lines: Using
strip()removes extra whitespace (like spaces before/after usernames or passwords) that could cause unexpected mismatches. - Safer file handling: The
withstatement ensures the file is properly closed after reading, avoiding resource leaks. - Simplified password check: Once we have the correct password for the user, we just loop until the input matches it directly.
Quick note on your text file format:
Make sure your Moradores.txt has each user on a separate line, formatted like this (no trailing | at the end of lines):
Randy Orton|RKO@gmail.com|rko2000 Undertaker|Taker@gmail.com|deadman21 Triple H|Thegame@gmail.com|HHH3
If your file has all users in one long line separated by |, let me know and I can adjust the code to handle that format!
内容的提问来源于stack exchange,提问作者VenomSnake

