python实现定时向文件写入数据

使用场景

        系统压力测试时,想简单记录一下系统什么时间死机。就用python写一个定时一分钟往txt文件写入当前时间的脚本。

实现代码


# !/usr/bin/python
# coding=UTF-8

import time
import os

# 生成log文件
def Numberlog():
    nowtime = time.strftime('%Y_%m_%d_%H_%M_%S',time.localtime(time.time()))
    print(nowtime)
    # 时间写入日志文件
    with open('time_log.txt','a+',newline='') as screen_log:
        screen_log.writelines(nowtime)
        screen_log.writelines("\n")
        screen_log.close()
# count=0
while True:
    Numberlog()
    # count += 1
    count=len(open('time_log.txt','r').readlines())
    # 记录一下写入次数
    with open('number.txt','w',newline='') as number:
        number.write(str(count))
        number.close()
    time.sleep(60) #定时60s看一下