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

登录系统与文本文件打印功能故障排查求助

问题分析与解决

问题1:正确账号需两次尝试才能登录

原因

你先调用了fileRead.read()读取整个文件内容到fileContents,这会把文件的读写指针移动到文件末尾。之后的fileRead.readline()从末尾开始读取,自然读不到任何行数据,导致第一次验证时找不到匹配的账号,触发重新输入逻辑。第二次调用option3()时,会重新打开文件,指针回到文件开头,才能正常读取行进行验证。

解决方法

有两种可行方案:

  • 方案一:读取完整个文件后,调用fileRead.seek(0)将指针移回文件开头,再执行逐行验证
  • 方案二:先逐行验证账号,验证成功后再读取整个文件内容(更高效,避免提前读取不必要的内容)

问题2:登录成功后无法打印文件内容

原因

  1. 代码中未导入time模块,执行time.sleep(2)会抛出异常,中断程序,无法执行后续的print(fileContents)
  2. 若第一次验证失败后调用的是option1()(而非option3()),递归逻辑错误,可能导致后续流程异常
  3. 第一次验证时,即便fileContents已读取,但因验证失败不会触发打印,用户可能误以为登录成功后无法打印

解决方法

  • 导入time模块
  • 修正递归调用:验证失败时应调用option3()而非option1()
  • 确保验证成功后能正常执行打印逻辑

修正后的代码

import time

def option3():
    print('\nGelos Enterprise User Accounts\n') 

    global index_num, userName, passWord, balances, username, password
    username = input("Enter your username : ")
    password = input("Enter your password : ")
    
    flag = False
    fileRead = open('accounts.txt', 'r')
    
    # 先逐行验证账号
    while True:
        line = fileRead.readline()
        if len(line) == 0:
            break
        lineItem = line.split()
        # 处理空行避免索引报错
        if len(lineItem) < 2:
            continue
        if username.strip() == lineItem[0] and password.strip() == lineItem[1]:
            print(f"\nHello {username}, you have logged in successfully.\n")
            print("Displaying all usernames and passwords: \n")
            time.sleep(2)
            # 验证成功后,将指针移回开头读取整个文件
            fileRead.seek(0)
            fileContents = fileRead.read()
            print(fileContents)
            flag = True
            break
    
    fileRead.close()  # 关闭文件,避免资源泄漏
    
    if not flag:
        print("\nThe user is not found.Please re-enter your username and password.\n")
        option3()  # 修正递归调用

额外优化点

  • 增加文件关闭操作,避免资源泄漏(也可用with语句实现自动关闭,更安全)
  • 处理文件中的空行,避免lineItem[1]索引越界报错
  • 使用f-string简化打印语句格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:51:13