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

验证用户输入的登录凭证与log.txt文件中存储信息的匹配性

登录凭证校验功能实现

需求:将用户输入的登录凭证(用户名、密码、角色)与log.txt文件中以“登录名 密码 角色\n”格式存储的信息进行校验。

原始Python代码(已翻译提示文本)

def login():
    temp = []
    print("登录仓库系统\n")
    name = str(input("请输入用户名:"))
    pas = str(input("请输入密码:"))
    role = str(input("请输入角色:"))
    if role == "admin" or role == "reworker":
        print("角色已识别!\n\n")
    else:
        # 原代码调用未定义的err函数,此处改为print输出
        print("未知角色!\n\n")
        login()
    with open('log.txt', 'r') as fs:
        text = fs.readlines()
        for x in text:
            if name in x and pas in x and x[2] == 'admin':
                print("管理员")
            elif name in x and pas in x and x[2] == 'reworker':
                print("工作人员")
            else:
                print("凭证错误!\n")

原始log.txt文件内容

mans 123 admin
mans 123 admin
Mansur 4950495 reworker
God 123 admin
hello 123 admin
ror 123 admin

代码问题说明

  • 原代码调用了未定义的err函数,会触发NameError,需改为print输出错误信息
  • 使用name in x和pas in x会导致部分匹配错误(例如输入用户名"man"会匹配到"mans"),应该精准匹配用户名和密码
  • x[2]取的是字符串的第三个字符而非角色字段(比如第一行x[2]是'n'),需拆分每行内容后获取角色

修正后的Python代码

def login():
    print("登录仓库系统\n")
    name = input("请输入用户名:").strip()
    pas = input("请输入密码:").strip()
    role = input("请输入角色:").strip()

    # 校验角色合法性
    if role not in ("admin", "reworker"):
        print("未知角色!\n")
        login()
    print("角色已识别!\n")

    # 读取并校验凭证
    valid = False
    with open('log.txt', 'r', encoding='utf-8') as fs:
        for line in fs:
            line = line.strip()
            if not line:
                continue
            stored_name, stored_pas, stored_role = line.split()
            if name == stored_name and pas == stored_pas and role == stored_role:
                valid = True
                break

    if valid:
        print("管理员登录成功" if role == "admin" else "工作人员登录成功")
    else:
        print("凭证错误!\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:10:39