Python实现用户输入Y后读取文本文件下一行的问题排查
问题根因
逐行读取重复返回第一行的核心原因是:每次触发继续读取的逻辑时,你都重新执行了打开facts.txt的操作。文件重新打开后,读取指针会自动回到文件起始位置,因此每次调用readline()拿到的永远是文件的第一行内容。
修复逻辑
- 整个读取事实的流程中只打开一次
facts.txt,不要在循环内重复打开文件 - 将打开的文件对象在读取逻辑中传递,每次调用
readline()时指针会自动向后偏移,就能顺序拿到下一行内容 - 增加文件读完的判断:当
readline()返回空字符串时,说明所有内容已经读取完毕,直接给出结束提示即可
修正后代码(仅调整逐行读取相关逻辑,其余原有逻辑保留)
# Defining functions def well_bot(): print("Hi there, my name is Well Bot. ") print("My job is to tell people general facts about mental health and different types of mental illnesses. ") info = get_info() print(info) # 原代码此处调用未定义的print_facts()会直接报错,按优先解决逐行读取问题的要求暂时注释,后续可自行补全 #this should only print if they want a fact # getfact = print_facts() # print(getfact) #var to read from illnesses text file to add later def get_info(): res = input("What can I teach you about today? \n[a] Facts \n[b] Types \n> ") if res == "a": print ("Okay. I will give you some general facts about mental health. ") with open('facts.txt') as facts: next_fact = facts.readline() print (next_fact) # 传入已打开的文件对象,避免后续重复打开文件 return continue_ask(facts) elif res == "b": return "Okay, I can tell you about two different mental illnesses: \n[1] Depression \n[2] Bipolar Disorder \n> " else: print_message() return get_info() def continue_ask(facts): while True: user_input = input("Want to know more? Enter Y to continue or N to finish: ") if user_input == "Y": next_fact = facts.readline() # 读到空内容说明文件已全部读取完毕 if not next_fact: print("No more mental health facts available for now!") print("Okay, thanks, bye! ") break print(next_fact) else: print ("Okay, thanks, bye! ") break def print_message(): print("I'm sorry, I didn't quite get that. Can you choose again? ") return get_info() #Call Bot well_bot()
说明:原代码
well_bot函数中调用了未定义的print_facts(),运行时会直接抛出错误,我按你提出的「优先解决逐行读取问题、暂不排查其他潜在问题」的要求将这两行临时注释,你后续可以根据功能规划补全对应逻辑。
内容的提问来源于stack exchange,提问作者sillysausage
相关产品推荐
相关产品推荐

