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

Python 3.9基于txt文件内容判断的If语句运行异常问题

问题根因
  • 核心问题为Python文件对象的read()方法特性导致:调用一次read()读取完整文件内容后,文件指针会移动到文件末尾,后续再调用read()只会返回空字符串,不会重新加载文件内容:
    1. 若你提前点击过「Show Password」按钮,show_password函数内的r1.read()已经将文件指针移到末尾,后续login函数中所有r1.read()调用返回值均为空,无法和输入密码匹配
    2. 即使没有点击过「Show Password」,login函数内你连续两次调用r1.read()做判断:if分支的r1.read()已经读取完全部内容,elif分支的r1.read()仍会返回空,必然进入sleep分支
  • 次要问题:全局文件对象r1打开后从未关闭,存在资源泄漏,也可能引发IO异常。
修复方案
  1. 去掉全局变量r1,单独封装密码读取方法,每次需要读取密码时临时打开文件、读取完成后自动关闭,规避文件指针偏移问题:
def get_saved_password():
    # with语法会自动关闭文件,无需手动调用close
    with open("newfile.txt", "r", encoding="utf-8") as f:
        # strip()用于消除内容首尾意外的空格、换行符,避免匹配干扰
        return f.read().strip()
  1. 修改show_password函数,调用封装好的方法读取密码:
def show_password():
    pwd = get_saved_password()
    print("Password is: %s" % pwd)
  1. 修改login函数逻辑,仅读取一次存储的密码再做对比,不要重复调用读文件操作:
def login():
    username = e1.get().strip()
    input_pwd = e2.get().strip()
    saved_pwd = get_saved_password()
    if username == "a" and input_pwd == saved_pwd:
        new_win = Tk()
        # 后续登录成功逻辑
    elif username == "a" and input_pwd != saved_pwd:
        sleep(5)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:54:04