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看一下

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
可以使用Python定时任务模块`schedule`来实现每半小时爬取数据写入表格的功能。具体实现步骤如下: 1. 安装`schedule`模块: ```python pip install schedule ``` 2. 导入相关模块: ```python import schedule import time import pandas as pd ``` 3. 定义一个函数,用于爬取数据写入表格: ```python def write_to_excel(): # 爬取数据并存储为DataFrame格式 data = pd.DataFrame(...) # 写入表格文件 with pd.ExcelWriter('data.xlsx', mode='a') as writer: data.to_excel(writer, sheet_name='Sheet1', index=False) ``` 4. 使用`schedule`模块的`every().minutes.do()`方法来定时执行函数: ```python schedule.every(30).minutes.do(write_to_excel) ``` 5. 使用无限循环来让程序一直运行: ```python while True: schedule.run_pending() time.sleep(1) ``` 完整示例代码如下: ```python import schedule import time import pandas as pd def write_to_excel(): # 爬取数据并存储为DataFrame格式 data = pd.DataFrame(...) # 写入表格文件 with pd.ExcelWriter('data.xlsx', mode='a') as writer: data.to_excel(writer, sheet_name='Sheet1', index=False) schedule.every(30).minutes.do(write_to_excel) while True: schedule.run_pending() time.sleep(1) ``` 注意,如果要在程序每次运行时清空表格并写入数据,可以在`write_to_excel`函数中添加一行代码: ```python pd.DataFrame().to_excel(writer, sheet_name='Sheet1', index=False) ``` 这样每次运行程序都会清空表格并写入数据

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林中云雾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值