我想编写一个python代码,它每隔x秒添加一个值。但是,当我添加time.sleep(x)时,.txt文件中就没有输出了。
有没有办法在一定时间后停止循环?
代码:
f = open('Log.txt','a')
while True:
print("This prints once a second.", file=f)
time.sleep(1)发布于 2020-06-11 12:39:37
也许是这样的:
import time
while True:
with open('Log.txt','a') as f:
f.write("This prints once a second.\n")
time.sleep(1)如果您想在给定的时间之后停止:
import time
stop_after = 10 # seconds
start = time.time()
while time.time() - start < stop_after:
with open('Log.txt','a') as f:
f.write("This prints once a second.\n")
time.sleep(1)发布于 2020-06-11 12:37:54
最好使用上下文管理器,这是可行的:
import time
while True:
with open('Log.txt','a') as f:
print("This prints once a second.",file=f)
time.sleep(1)https://stackoverflow.com/questions/62324552
复制相似问题