Python登录信息文件校验代码问询:注册与登录逻辑优化
修复Python文件登录信息校验逻辑
原代码存在的问题
- 登录校验时未正确读取文件内容,
logininfo变量未定义,且username in ('logininfo')是判断字符串字面量,而非文件中的用户名 - 仅校验用户名,未匹配对应的密码,登录逻辑不完整
- 文件操作未使用上下文管理器(
with),存在资源泄漏风险 - 注册循环退出逻辑不合理(
choice=choice+choice+choice)
修正后的实现代码
1. 用户注册功能(追加登录信息到文件)
while choice == '1': username = input('enter a name: ') if username == '': print('user name cant be blank') else: print('hello', username, 'welcome to the quiz') password = input('please enter a password that is 4 characters long: ') while len(password) < 4: password = input('please enter a password that is 4 characters long: ') # 使用with语句自动管理文件,无需手动close with open("logininfo", "a") as f: f.write('---------\n') f.write(f"{username}\n") f.write(f"{password}\n") f.write('---------\n') print('welcome you may now begin') # 修改退出循环的逻辑,让流程更合理 choice = input("Enter '1' to register another user, or other key to exit: ")
2. 用户登录校验功能(验证文件中的登录信息)
while choice == '2': print('enter your log in details') input_username = input('username: ') input_password = input('password: ') login_success = False # 读取文件内容并按存储格式校验 with open('logininfo', 'r') as f: lines = f.readlines() # 按「分隔线+用户名+密码+分隔线」的分组格式遍历 for i in range(0, len(lines), 4): stored_username = lines[i+1].strip() stored_password = lines[i+2].strip() if stored_username == input_username and stored_password == input_password: login_success = True break if login_success: print('welcome back!') break # 登录成功后退出循环 else: print('invalid username or password') # 让用户选择重新尝试或退出 choice = input("Enter '2' to try again, or other key to exit: ")
关键改进说明
- 用
with open(...) as f自动处理文件的打开与关闭,避免资源泄漏 - 登录校验时严格按照文件存储的分组格式读取,精准匹配用户名和对应密码
- 优化循环退出逻辑,符合用户操作预期
- 增加登录状态标记,清晰判断校验结果
内容的提问来源于stack exchange,提问作者Zacomacpac
相关产品推荐
相关产品推荐

