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

Python读取多行列文本文件实现登录时仅新用户可用问题求助

问题分析与修复

错误原因

  • 登录代码里的for line in user循环会遍历所有用户行,但每次循环都会把data变量覆盖成当前行的拆分结果,循环结束后data只保留了最后一行用户的账号信息,所以只能识别最后添加的用户,之前的admin账号自然无法匹配。
  • 原代码中username变量在使用前没有初始化,运行时会直接抛出未定义的错误。

修正后的登录代码

# 先让用户输入用户名
username = input("Please enter your username: ")

# 读取用户文件并验证账号
with open("user.txt", "r") as file:
    users = file.readlines()
    user_found = False
    matched_password = ""
    
    for line in users:
        # 移除行尾的换行符,避免拆分出错
        line = line.strip()
        # 跳过空行(比如文件末尾可能存在的空行)
        if not line:
            continue
        # 拆分用户名和密码
        user_username, user_password = line.split(", ")
        # 匹配到输入的用户名就记录密码并终止循环
        if username == user_username:
            user_found = True
            matched_password = user_password
            break

# 根据匹配结果处理后续流程
if not user_found:
    print("Username not recognised!")
else:
    password = input("Please enter your password: ")
    while password != matched_password:
        password = input("Sorry, that password is wrong, please try again: ")
    print("\nThank you. Logging in...\n")

可选优化:注册时检查重复用户名

原注册代码允许重复添加相同用户名,会导致账号冲突,可添加检查逻辑:

while True:
    menu = input('''Select one of the following Options below:
r - Registering a user
a - Adding a task
va - View all tasks
vm - view my task
e - Exit
: ''').lower()

    if menu == 'r':
        # 检查用户名是否已存在
        def check_username_exists(new_user):
            with open("user.txt", "r") as file:
                for line in file.readlines():
                    line = line.strip()
                    if not line:
                        continue
                    existing_user, _ = line.split(", ")
                    if existing_user == new_user:
                        return True
            return False
        
        # 循环直到输入未被使用的用户名
        while True:
            new_user = input("Please enter a new username: ")
            if check_username_exists(new_user):
                print("This username is already taken, pick another one.")
            else:
                break
        
        new_password = input("Please enter a new password: ")
        password_confirmation = input("Please confirm your password: ")          
        while new_password != password_confirmation:
            new_password = input("Sorry, passwords don't match. Enter new password: ")
            password_confirmation = input("Confirm your password again: ")
        
        with open("user.txt", "a") as file: 
            file.write("\n" + new_user + ", " + new_password)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:25:33