Python实现txt文件用户名匹配仅识别最后一条记录问题排查
问题根因
你的用户名校验逻辑有两个核心bug:
- 遍历
accountdetails.txt每行内容时,createdUser变量会被每一行读到的用户名反复覆盖,循环跑完后这个变量只会存文件最后一行的kai,前面存的max、nicky、tom全被覆盖掉了,根本校验不到。 - 用
createUser in createdUser是判断输入内容是不是当前用户名的子串,不是精确匹配用户名,比如输入ka都会被判定为和kai重复,判断逻辑本身就不对。
另外代码还有几个隐性坑:
- 打开文件从来没关过,跑的次数多了容易触发文件占用报错
- 读到文件里的空行时,
split()会返回空列表,直接取索引0/1会触发索引越界错误 - 写新账号的时候多打了个前置换行,文件里会攒一堆没用的空行
- 每次注册、登录都要重新读一遍全量文件,重复逻辑太多
- 没有处理用户输入首尾误输入空格的场景,容易出现校验误判
修正后完整代码
from time import sleep import time users = {} # 统一抽离文件路径常量,后续改路径不用到处找 ACCOUNT_FILE_PATH = r"C:\Users\User\Desktop\Python Project\accountdetails.txt" status = "" # 抽离公共的用户数据加载函数,避免重复写读文件逻辑 def load_all_users(): user_dict = {} # 用with上下文管理器自动处理文件关闭,避免文件占用 with open(ACCOUNT_FILE_PATH, "r", encoding="utf-8") as f: for line in f: line = line.strip() # 跳过空行,避免索引报错 if not line: continue user_info = line.split() # 跳过格式错误的行(比如缺密码),避免运行崩溃 if len(user_info) >= 2: username, password = user_info[0], user_info[1] user_dict[username] = password return user_dict def loading(): spaces = 0 while spaces < 3: print("Loading" + "." + " " + "." + " " + "." + " " + "." + " " ) spaces = spaces + 1 sleep(1) def mainMenu(): global status status = input("Do you have a login account? y/n Or press q to quit\n") if status == "y": oldUser() elif status == "n": newUser() elif status == "q": quit() def newUser(): createUser = input("Please create a username: ").strip() # 加载全量已存在用户做校验 exist_users = load_all_users() # 用字典键做精确匹配,不会出现子串误判 if createUser in exist_users: print("\nUsername already exist!\n") return createPass = input("Please type a new password: ").strip() users[createUser] = createPass print("\nAccount Created\n") # 追加写入新账号,去掉多余前置换行 with open(ACCOUNT_FILE_PATH, "a", encoding="utf-8") as f: f.write(f"{createUser} {createPass}\n") def oldUser(): userInput = input("Enter username: ").strip() passwInput = input("Enter password: ").strip() exist_users = load_all_users() if
相关产品推荐
相关产品推荐

