Python登录系统登录失败问题:已注册用户无法正常登录
Python登录系统CSV验证问题:已注册用户登录失败
我正在开发学校项目的Python登录系统,将用户注册的用户名和密码存储到CSV文件中。新用户注册功能正常,但已注册用户尝试登录时,总会提示「用户名或密码错误」。
现有代码
import csv import random # create a list to store the usernames and passwords of both players players = [] # loop through each player for i in range(2): # ask if the player has made a username and password before newUser = input(f"Player {i+1}, have you made a username and password before?").strip() # if the player is new, ask for their name and password and add them to the list if newUser == 'no': newName = input(f"Player {i+1}, what is your first name?").strip() newPassword = input(f"Player {i+1}, what would you like your password to be?").strip() players.append([newName, newPassword]) file = open('ScoreSheet.csv', 'a', newline='') writer = csv.writer(file) writer.writerow([newName, newPassword]) file.close() # if the player has logged in before, ask for their name and password and check if they match elif newUser == 'yes': verifyName = input(f"Player {i+1}, what is your name?").strip() verifyPassword = input(f"Player {i+1}, what is your password?").strip() # loop through each player's login information and check if there is a match match_found = False for player in players: if player == [verifyName, verifyPassword]: print(f"Player {i+1}, you are logged in") match_found = True break # if there is no match, inform the player and ask them to try again if not match_found: print(f"Player {i+1}, wrong username or password. Please try again.") # print welcome message with the players' names if len(players) >= 2: print(f"Welcome, {players[0][0]} and {players[1][0]}!") else: print("Error: not enough players logged in.")
CSV文件情况
我用Google Sheets创建了CSV文件,格式为name,password,score:
- 在Google Sheets中查看时,显示所有已注册用户信息:
'finley' 'fin' '10' janet janet123 None james james123 None charlie charlie123 None amy amy123 None fred fred123 None summer summer123 None nat nat123 None nathan nathan123 None elle elle123 None charles charles123 None juno juno123 None sam sam123 None samuel samuel123 None Tom Tom123 None Thomas Thomas123 None charlie charlie123 None grace grace123 None natalie natalie123 None Dan Dan123 None Daniel Daniel123 None
- 但在VS Code中打开该文件时,只显示两行:
finley,fin,10 janet,janet123
我是CSV新手,使用PyScripter运行代码,求解决办法。
问题根源
- 未读取已有用户数据:当前代码的
players列表仅存储本次运行中注册的新用户,完全没有从CSV文件读取已存在的用户信息,导致老用户登录时找不到匹配项。 - CSV写入格式不兼容:代码注册新用户时只写入
name和password两个字段,但CSV定义的格式是name,password,score三字段,缺失的字段导致文件格式混乱,不同编辑器解析结果不一致。 - CSV文件格式异常:Google Sheets创建的文件可能存在分隔符不统一、额外字符或空行问题,导致VS Code读取异常。
修复后的代码
import csv # 程序启动时从CSV读取已有用户数据 players = [] try: with open('ScoreSheet.csv', 'r', newline='', encoding='utf-8') as file: reader = csv.reader(file) # 跳过表头(如果文件已存在表头) header = next(reader) for row in reader: # 确保行数据至少包含name和password字段 if len(row) >= 2: players.append([row[0].strip(), row[1].strip()]) except FileNotFoundError: # 如果文件不存在,创建新文件并写入表头 with open('ScoreSheet.csv', 'w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(['name', 'password', 'score']) # 处理两位玩家的登录/注册流程 for i in range(2): newUser = input(f"Player {i+1}, 你之前注册过吗?(yes/no)").strip().lower() if newUser == 'no': newName = input(f"Player {i+1}, 请输入你的名字:").strip() newPassword = input(f"Player {i+1}, 请设置你的密码:").strip() # 新用户默认分数为0 players.append([newName, newPassword]) # 按CSV格式写入完整字段 with open('ScoreSheet.csv', 'a', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow([newName, newPassword, 0]) print(f"Player {i+1}, 注册成功!") elif newUser == 'yes': verifyName = input(f"Player {i+1}, 请输入你的名字:").strip() verifyPassword = input(f"Player {i+1}, 请输入你的密码:").strip() match_found = False for player in players: # 单独匹配用户名和密码,避免列表长度不一致导致的匹配失败 if player[0] == verifyName and player[1] == verifyPassword: print(f"Player {i+1}, 登录成功!") match_found = True break if not match_found: print(f"Player {i+1}, 用户名或密码错误,请重试。") # 输出欢迎信息 if len(players) >= 2: print(f"欢迎,{players[0][0]} 和 {players[1][0]}!") else: print("错误:登录的玩家数量不足。")
额外建议
- 统一CSV格式:所有写入操作严格遵循
name,password,score三字段格式,避免格式混乱。 - 规范文件操作:使用
with语句自动管理文件关闭,避免资源泄漏。 - 数据清洗:输入和读取数据时用
strip()去除多余空格,避免因空格导致匹配失败。 - 编辑器选择:尽量用VS Code等纯文本编辑器创建/编辑CSV文件,避免Google Sheets导出时的格式兼容问题。
内容的提问来源于stack exchange,提问作者fcorby
相关产品推荐
相关产品推荐

