python - 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)
解决方案
最好使用上下文管理器,这很有效:
import time
while True:
with open('Log.txt','a') as f:
print("This prints once a second.",file=f)
time.sleep(1)
推荐阅读
- java - Android 水平滚动视图
- c# - 在 Azure 中横向扩展应用服务时,是否在所有实例上处理单个消息(来自队列)?
- sql - 如何从存储过程/函数中获取代码注释并填充到表中?
- html - 移动文件后 CSS 未正确链接
- sql-server - 将数据 VARCHAR 转换为数字
- android - 登录时在 Android Studio 中显示 Firebase 用户名?
- ios - 如何使网页在 iOS 应用中自动滚动?
- bash - Mac OS Mojave 终端:保存每个选项卡的历史记录
- mysql - 需要将数据库转储导出为带有标题和行的 csv 格式
- android - Kotlin 的永久旋转动画