Python代码无法将输出写入output.txt文件,如何修正?
解决Python无法将输出写入文件的问题
你的代码无法写入output.txt的核心原因是未正确刷新或关闭文件缓冲区。当替换sys.stdout为文件对象后,Python的输出会暂存于内存缓冲区中,若不主动触发写入操作,内容不会同步到磁盘。
修正方案1:手动关闭文件
在程序结束前关闭重定向的文件对象,强制将缓冲区内容写入磁盘:
import sys,os if not os.environ.get("ONLINE_JUDGE"): sys.stdin=open('./input.txt','r') sys.stdout=open('./output.txt','w') import time start_time=time.time() print("Hello World") print("______ %s seconds ____"%(time.time()-start_time)) # 关闭文件,确保缓冲区内容写入 if not os.environ.get("ONLINE_JUDGE"): sys.stdout.close() sys.stdin.close()
修正方案2:使用with语句(更推荐)
with语句会自动管理文件生命周期,执行完毕后自动关闭文件,避免手动关闭的遗漏:
import sys,os import time start_time=time.time() if not os.environ.get("ONLINE_JUDGE"): with open('./input.txt','r') as f_in, open('./output.txt','w') as f_out: sys.stdin = f_in sys.stdout = f_out print("Hello World") print("______ %s seconds ____"%(time.time()-start_time)) else: print("Hello World") print("______ %s seconds ____"%(time.time()-start_time))
修正方案3:手动刷新缓冲区
如果不需要提前关闭文件,可在打印后手动刷新缓冲区:
import sys,os if not os.environ.get("ONLINE_JUDGE"): sys.stdin=open('./input.txt','r') sys.stdout=open('./output.txt','w') import time start_time=time.time() print("Hello World") print("______ %s seconds ____"%(time.time()-start_time)) # 强制刷新缓冲区到磁盘 sys.stdout.flush()
额外注意:确保input.txt和output.txt与脚本在同一目录下,否则需调整文件路径为绝对路径。
内容的提问来源于stack exchange,提问作者Akash Kp
相关产品推荐
相关产品推荐

