无限while循环下TXT文件写入失败问题求助
解决无限循环中无法写入TXT文件的问题
嘿,我来帮你捋清楚问题出在哪,以及怎么调整代码就能实现实时写入文件的效果:
问题根源
你遇到的情况主要是两个小问题导致的:
- 文件缓冲区没及时刷新:Python默认会把文件写入的内容暂时存在内存缓冲区里,不会立刻写到硬盘上——除非缓冲区满了,或者你主动关闭文件。你把文件打开的操作放在了循环外面,又没手动触发刷新,所以循环里的写操作看起来像是没生效。
- 时间戳只取了一次:你的
date变量是在循环开始前定义的,所有ping失败的记录都会显示程序启动时的时间,而不是实际故障发生的时间,这显然不符合你的需求。
推荐修改方案(两种可选)
方案一:每次写入时打开/关闭文件(更稳妥)
这种方式用with语句管理文件,每次写入都会自动刷新缓冲区,不用担心忘记关闭文件的问题:
import os import datetime import time # 加个延时,避免循环太占CPU hostnames = [ '192.168.1.1', '192.168.1.2', '192.168.1.3', ] while True: # 每次循环都获取当前时间,保证记录的是实时时间 current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") for hostname in hostnames: # Windows用Ping,Linux/macOS改成ping即可 ping_result = os.system(f"Ping {hostname}") if ping_result != 0: # 跨平台兼容,ping失败返回非0值 print(f"{hostname} DOWN") # 用with打开文件,写入后自动关闭,强制刷新内容到硬盘 with open("log.txt", "a", encoding="utf-8") as log_file: log_file.write(f"{current_time} {hostname}\n\n") else: print(f"{hostname} UP") time.sleep(5) # 每隔5秒轮询一次,可根据需求调整间隔
方案二:保持文件打开,手动刷新缓冲区
如果不想每次都打开关闭文件,也可以把文件打开放在循环外,每次写入后手动刷新:
import os import datetime import time hostnames = [ '192.168.1.1', '192.168.1.2', '192.168.1.3', ] # 用with保持文件打开状态,自动处理关闭 with open("log.txt", "a", encoding="utf-8") as log_file: while True: current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") for hostname in hostnames: ping_result = os.system(f"Ping {hostname}") if ping_result != 0: print(f"{hostname} DOWN") log_file.write(f"{current_time} {hostname}\n\n") log_file.flush() # 手动刷新缓冲区,立刻写入文件 else: print(f"{hostname} UP") time.sleep(5)
额外小提示
- 时间戳我用了
strftime格式化,这样日志里的时间会更清晰易读,你可以根据自己的需求调整格式。 - 不同系统的ping返回值可能有差异,用
ping_result != 0比直接判断==1更兼容Linux/macOS环境。 - 加入
time.sleep()是为了避免循环太频繁占用过多CPU资源,你可以根据监控需求调整间隔时间。
内容的提问来源于stack exchange,提问作者Micky
相关产品推荐
相关产品推荐

