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

如何检测文件中是否存在指定内容?Python读取LOGINS.txt无返回问题排查

核心问题
  1. a+模式打开文件时,文件指针默认定位在文件末尾,直接执行f.read()只会从末尾开始读取,拿到的是空内容,所以永远判断不到已存在的用户名。
  2. Q变量仅在代码初始化时赋值为False,第一次走完子循环后Q一直为True,后续主循环进入未授权分支时,子循环永远不会执行。
修复方案
  • 读取文件内容前调用f.seek(0),将文件指针移动到文件头部,保证能读取到完整的文件内容。
  • 每次主循环开始时重置Q变量为False,保证后续循环的子分支能正常执行。
  • 你使用的with上下文管理器会自动在代码块结束时关闭文件,不需要手动调用关闭方法,不影响后续逻辑的文件操作,下次使用重新打开即可。
修复后代码
D = False
# ^ 主循环

while D != True:
    # 每次主循环重置子循环标记
    Q = False
    player1 = input("What is Player 1's name?\n")

    with open("LOGINS.txt", "a+") as f:
        # 移动文件指针到开头再读取
        f.seek(0)
        w = f.read()
        if player1 in w:
            print("Authorised")
        else:
            un_player1 = input("Not currently authorised, would you like to add your name to the list? Y/N.\n")
            while Q != True:
                if un_player1 == "Y":
                    f.writelines(str(player1) + "\n")
                    print("Registered.")
                    Q = True
                else:
                    print("Bye!")
                    Q = True
                    D = True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:06:01