You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python csvwriter每日生成带日期的锅炉日志CSV文件?

按日生成锅炉日志文件的Python脚本修改方案

原脚本每10秒从锅炉数据总线读取参数并写入单个CSV文件,现需调整为每24小时生成一个含当日日期的独立日志文件,修改后的完整代码如下:

from subprocess import check_output, Popen, PIPE
import csv
from datetime import datetime
import threading

bai = ['/usr/bin/ebusctl', 'read', '-c', 'bai', '-f']
f39 = ['/usr/bin/ebusctl', 'read', '-c', 'f39', '-f']
header = ['Date','Time','Flow','Return','Flame','Modulation','Flow Temp Desired','Energy CH','Energy HW','Room Temp']

def read_ebus():
    threading.Timer(10.0, read_ebus).start()
    # 获取当前日期,用于生成当日日志文件名
    current_date = datetime.today().strftime('%Y-%m-%d')
    log_filename = f'/media/pi/boiler_log_{current_date}.csv'
    
    time = datetime.today().strftime('%H:%M:%S')
    flow_temp = float(check_output(bai+['FlowTemp', 'temp']))
    return_temp = float(check_output(bai+['ReturnTemp', 'temp']))
    flame = Popen([*bai, 'Flame'], stdout=PIPE, stderr=PIPE).communicate()[0].decode().strip()
    modulation = float(check_output(bai+['ModulationTempDesired']))
    flow_temp_desired = float(check_output(bai+['FlowTempDesired']))
    energy_ch = int(check_output(bai+['PrEnergySumHc1']))
    energy_hw = int(check_output(bai+['PrEnergySumHwc1']))
    room_temp = float(check_output(f39+['RoomTemp', 'temp']))
    
    data = [current_date, time, flow_temp, return_temp, flame, modulation, flow_temp_desired, energy_ch, energy_hw, room_temp]
    
    # 判断当日日志文件是否存在,不存在则先写入表头
    file_exists = False
    try:
        with open(log_filename, 'r'):
            file_exists = True
    except FileNotFoundError:
        pass
    
    with open(log_filename, 'a', newline='') as f:
        writer = csv.writer(f)
        if not file_exists:
            writer.writerow(header)
        writer.writerow(data)

read_ebus()

关键改动说明

  • 动态生成每日文件名:通过current_date拼接出形如boiler_log_2024-05-20.csv的文件名,确保每天对应独立文件
  • 自动写入表头:每次写入前检查当日文件是否存在,不存在则先写入表头,避免重复表头或文件无表头的问题
  • 移除初始文件创建逻辑:删掉原脚本开头创建单个boiler_log.csv的代码,改为按需创建每日文件
  • 保留原有数据读取逻辑:保持每10秒读取锅炉参数的定时任务和数据解析逻辑不变

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:23:14