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

如何用Pandas Dataframe实现车辆计数CSV日志的追加写入

实现车辆计数CSV日志的追加写入

要实现每分钟将数据追加到同一个CSV文件而非生成新文件,只需对现有代码做以下几处修改:

  • 固定日志文件名,不再随分钟生成新文件名
  • 使用追加模式写入CSV,并控制表头仅在文件首次创建时写入
  • 调整时间戳相关逻辑,确保每行数据的时间信息准确

修改后的代码如下:

output_directory = save_dir
# 固定文件名,不再包含分钟级时间戳
file_name = 'Counting_Result.csv'
output_file_path = os.path.join(output_directory, file_name)

end_inf = datetime.now()
count_result = {
    'Start Inference': [end_inf],
    'Finish_Inference': [datetime.now().strftime("%Y%m%d_%H%M%S")],
    'Elapsed_Time': [end_inf - start_inf],
    'Up_direction': [up_count],
    'Down_direction': [down_count],
    'Car_total': [car_count],
    'mtrcycle_total': [motor_count],
    'bus_total': [bus_count],
    'truck_total': [truck_count]
}

df = pd.DataFrame(count_result)

# 判断文件是否存在,决定是否写入表头
file_exists = os.path.isfile(output_file_path)
# mode='a' 表示追加写入,header=not file_exists 确保仅首次创建文件时写表头
df.to_csv(output_file_path, mode='a', header=not file_exists, index=None)

关键修改说明:

  1. 固定文件名:去掉原代码中文件名的_%M分钟后缀,确保所有数据都写入同一个Counting_Result.csv文件
  2. 追加模式:mode='a'让pandas以追加方式打开文件,每次写入都会在文件末尾添加新行
  3. 表头控制:通过os.path.isfile()判断文件是否存在,避免后续追加时重复写入表头,保证CSV格式规范
  4. 时间信息保留:每行数据的Finish_Inference依然保留精确到秒的时间戳,方便后续追溯每条记录的生成时间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:53:16