首页 > 解决方案 > Python-3.x time.sleep() 不适用于打印到文件

问题描述

我想编写一个每 x 秒添加一个值的 python。但是当我将time.sleep(x)没有输出添加到 .txt 文件中时。

有没有办法在一段时间后停止循环?

代码:

f = open('Log.txt','a')
while True:
    print("This prints once a second.", file=f)
    time.sleep(1)

标签: pythonpython-3.xwhile-loop

解决方案


最好使用上下文管理器,这很有效:

import time

while True:
    with open('Log.txt','a') as f:
        print("This prints once a second.",file=f)
    time.sleep(1)

推荐阅读