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

Python账号密码校验时可识别用户名但无法识别密码问题求解

问题根因
  • 你从文件中逐行读取内容时,每行末尾默认携带换行符\n,拆分后得到的密码字段末尾会附带这个多余的换行符,和用户输入的无特殊字符的密码无法匹配。
修复方案
  1. 读取每行内容后先调用strip()方法移除首尾的空白字符(包含换行符、空格、制表符等),再按逗号拆分
  2. 可选优化:使用with语句管理文件句柄,无需手动调用close()方法,避免异常场景下文件资源泄漏;匹配到符合条件的账号后可以提前终止遍历,提升效率
修正后完整代码
class Account():
    def __init__(self, name, password):
        self.name = name
        self.password = password

username_input = input("Enter the name: ")
userpassword_input = input("Enter password: ")

data = []
# 使用with自动管理文件资源
with open('account information.txt', 'r', encoding='utf-8') as file:
    for line in file:
        # 先去除首尾空白字符再处理
        cleaned_line = line.strip()
        # 跳过空行避免报错
        if not cleaned_line:
            continue
        temp = cleaned_line.split(',')
        # 校验行格式合法性
        if len(temp) == 2:
            data.append(Account(temp[0], temp[1]))

is_exists = False
for d in data:
    if username_input == d.name and userpassword_input == d.password:
        is_exists = True
        # 匹配成功直接终止遍历
        break

if is_exists:
    print("欢迎登录")
else:
    print("您输入的账号或密码信息错误")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:06:03