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

Python 3注册系统无法识别已占用用户名问题求助

解决Python注册系统中"用户名已被占用"检测失效的问题

嘿,我看到你刚入门Python就动手做注册登录系统,遇到重复用户名检测失效的问题太正常了,咱们一步步拆解问题、修复它!

核心问题排查

先看你代码里导致检测失效的关键问题:

  1. 用户名匹配逻辑错误:你用if username in userdata直接判断文件对象里的内容,但文件中存储的用户名是带换行符\n的(因为你写入时用了f'{username}\n'),直接匹配会因为换行符的存在导致无法命中已注册的用户名。
  2. 全局文件对象的隐患:你在全局作用域提前打开了Users.txt,注册成功后又关闭了它,后续如果因为密码错误或用户名重复再次调用register(),会触发文件已关闭的报错。
  3. 登录函数的拼写错误:Hqeustion应该是Hquestion,这会导致登录逻辑无法正确触发。
  4. 登录逻辑的小缺陷:原代码只会检查文件中第一个用户,不匹配就直接重启登录,后面的用户永远不会被验证。

分步修复方案

1. 正确检测已注册用户名

读取文件时去掉每行的换行符和空白字符,再做匹配:

with open('Users.txt', mode = 'r') as userdata:
    # 提取所有已注册的用户名(去掉换行符)
    existing_usernames = [line.strip() for line in userdata.readlines()]
    if username in existing_usernames:
        print("username already taken!")
        return register()

2. 避免全局文件对象

删掉全局的Users = open('Users.txt', mode = 'a'),改用with语句在需要写入时临时打开文件,自动管理关闭:

# 注册成功后写入用户名
with open('Users.txt', mode = 'a') as users_file:
    users_file.write(f'{username}\n')

3. 修复登录函数的拼写错误

把Hqeustion改成正确的Hquestion:

def login():
    if Hquestion == "Y" or Hquestion == "y":
        # 后续登录逻辑不变

4. 优化登录验证逻辑

遍历所有用户后再判断是否匹配,避免只检查第一个用户:

def login():
    if Hquestion == "Y" or Hquestion == "y":
        loginuser = input('Write your username: ')
        loginpass = input('Write your password: ')
        found = False
        for user_pass in open('Logindata.txt', mode = 'r').readlines():
            loginsplit = user_pass.strip().split()
            # 确保分割后有足够元素,避免索引错误
            if len(loginsplit) >= 2 and loginuser == loginsplit[0] and loginpass == loginsplit[1]:
                print("You have successfully logged in! Enjoy shopping in Tomer's Shop!")
                found = True
                break
        if not found:
            print("Your username or password is wrong, please try again")
            return login()

5. 可选体验优化

  • 提前验证姓名格式,不用等输入完密码才报错
  • 密码验证不通过时只重新输入密码,不用从头填写所有信息

修复后的完整代码

import re

Hquestion = input("\t\t If you already registered please press Y, if you need to register please press N")

def register():
    if Hquestion.lower() == "n":
        firstname = input('please write your first name(only a-zA-Z allowed): ')
        # 先验证姓名格式
        namepattern = re.findall('[0-9!@#$%^&*()-+=?/".,{}\:;~]', firstname)
        if namepattern:
            print("Please use only a-z A-Z characters for first name!\n")
            return register()
        
        username = input('Enter Username : ')
        # 检测用户名是否已存在
        with open('Users.txt', mode = 'r') as userdata:
            existing_usernames = [line.strip() for line in userdata.readlines()]
            if username in existing_usernames:
                print("username already taken!")
                return register()
        
        # 密码验证,不通过则重新输入
        passpattern = re.compile('[a-zA-Z0-9@#$%^&*()-+=?/".,{}\:;~]{8,}')
        password = input ('Enter Password (using only a-zA-Z0-9!@#$%^&*. min 8 characters) : ' )
        while not passpattern.match(password):
            print("Your password is invalid. Please make sure your password is at least 8 characters long!\n")
            password = input('Enter Password again: ')
        
        # 写入用户数据
        with open('Users.txt', mode = 'a') as users_file:
            users_file.write(f'{username}\n')
        with open('Logindata.txt', mode = 'a') as logindata:
            logindata.write(f'{username} {password} {firstname}\n')
        
        print("Registration successful!")

def login():
    if Hquestion.lower() == "y":
        loginuser = input('Write your username: ')
        loginpass = input('Write your password: ')
        found = False
        for user_pass in open('Logindata.txt', mode = 'r').readlines():
            loginsplit = user_pass.strip().split()
            if len(loginsplit) >= 2 and loginuser == loginsplit[0] and loginpass == loginsplit[1]:
                print("You have successfully logged in! Enjoy shopping in Tomer's Shop!")
                found = True
                break
        if not found:
            print("Your username or password is wrong, please try again")
            return login()

# 根据用户选择调用对应函数,避免同时执行注册和登录
if Hquestion.lower() in ['y', 'n']:
    register() if Hquestion.lower() == 'n' else login()
else:
    print("Invalid input, please restart the program and enter Y or N")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:39:06