Python文本文件内容有时无法显示的问题求助
解决Python闪卡程序停止打印文本内容的问题
问题根源
- 文件指针位置问题:一次性打开所有文件后,第一次调用
read()会将文件指针移动到文件末尾,后续再调用read()时,指针停留在末尾,只会返回空字符串,导致看起来没有内容输出。 - 代码笔误:代码存在两处错误:
- 匹配到"F"时,实际调用的是
E.read() - 匹配到"G"(else分支)时,实际调用的是
F.read()
- 匹配到"F"时,实际调用的是
修复后的代码
只需在每次调用read()前,用seek(0)将文件指针重置到文件开头,同时修正两处笔误:
import time import random A = open("A.txt","r") B = open("B.txt","r") C = open("C.txt","r") D = open("D.txt","r") E = open("E.txt","r") F = open("F.txt","r") G = open("G.txt","r") notes = ["A","B","C","D","E","F","G"] i = 1 while i == 1: note = random.choice(notes) if note == "A": A.seek(0) # 重置文件指针到开头 print(A.read()) time.sleep(3) print("RESET A") elif note == "B": B.seek(0) print(B.read()) time.sleep(3) print("RESET B") elif note == "C": C.seek(0) print(C.read()) time.sleep(3) print("RESET C") elif note == "D": D.seek(0) print(D.read()) time.sleep(3) print("RESET D") elif note == "E": E.seek(0) print(E.read()) time.sleep(3) print("RESET E") elif note == "F": F.seek(0) # 修正笔误:从E改为F print(F.read()) time.sleep(3) print("RESET F") else: G.seek(0) # 修正笔误:从F改为G print(G.read()) time.sleep(3) print("RESET G")
说明
seek(0)的作用是将文件读取指针重新定位到文件起始位置,确保每次调用read()都能读取完整的文件内容。- 修正分支中的文件对象错误,保证每个分支读取对应文件的内容。
内容的提问来源于stack exchange,提问作者Xtreme
相关产品推荐
相关产品推荐

