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

求助:如何将命令输出完整导出为CSV表格?Python脚本问题

命令输出转CSV表格的问题解决

原脚本问题分析

原脚本仅手动处理了表头(table[0])和某一行数据(table[5]),没有遍历所有数据行,且手动拼接逗号容易引发CSV格式错误(比如单元格内容含逗号时)。

修改后的脚本(完整导出CSV)

from __future__ import print_function
from datetime import date 
import sys
import os
import time
import csv  # 导入Python内置CSV处理模块

today1 = date.today().strftime('%Y_%m_%d')
strTime = time.strftime('%Y_%m_%d')
  
command = 'My command here'
cmd = session.command()
response = cmd.execute(command)
element_group = response.get_output()

table = element_group.groups()[0]

# 打开CSV文件,自动处理文件关闭
with open(f'{today1}_output.csv', 'w', newline='', encoding='utf-8') as csvfile:
    csv_writer = csv.writer(csvfile)
    
    # 写入表头:提取table第一行的所有标签
    header_row = [cell.labels()[0] for cell in table[0]]
    csv_writer.writerow(header_row)
    
    # 遍历所有数据行(跳过表头行)
    for row in table[1:]:
        # 提取当前行每个单元格的值
        data_row = [cell.value() for cell in row]
        csv_writer.writerow(data_row)

print("CSV文件已生成完成")

关键改进点

  • 用csv模块替代手动拼接:自动处理CSV格式规则,比如单元格含逗号/引号时的转义,避免格式混乱
  • 遍历所有行:通过table[1:]遍历表头之外的所有数据行,确保完整导出表格内容
  • 安全文件操作:with open(...)语法自动管理文件资源,无需手动关闭文件
  • 自定义文件名:用日期作为文件名前缀,方便区分不同时间的导出结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:21:24