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

如何编写Python函数实现CSV转带多测试用例的YAML格式

CSV转YAML的Python函数实现方案

需求说明

输入CSV内容

name,description,tests
product_id,ID of the product,not null|unique
product_name,Name of the product,not null

期望输出YAML格式

- name : product_id
   description: ID of the product
   tests:
   - not null
   - unique
 - name: product_name
   description: Name of the product
   tests: 
   - not null

完善后的完整代码

import csv
import yaml

def csv_to_yaml(csv_file_path, yaml_file_path):
    result = []
    with open(csv_file_path, 'r', encoding='utf-8') as csv_file:
        datareader = csv.reader(csv_file)
        data_headings = []
        tests_index = -1
        
        for row_index, row in enumerate(datareader):
            if row_index == 0:
                # 处理表头,提取字段名并记录tests列的索引
                for heading_index, heading in enumerate(row):
                    fixed_heading = heading.lower().replace(" ", "_").replace("-", "")
                    data_headings.append(fixed_heading)
                    if fixed_heading == "tests":
                        tests_index = heading_index
            else:
                content = {}
                for cell_index, cell in enumerate(row):
                    heading = data_headings[cell_index]
                    # 处理tests字段,按|分割为列表
                    if cell_index == tests_index and cell:
                        content[heading] = [item.strip() for item in cell.split("|")]
                    else:
                        content[heading] = cell.strip() if cell else ""
                result.append(content)
        
        # 将转换后的数据写入YAML文件
        with open(yaml_file_path, 'w', encoding='utf-8') as yaml_file:
            yaml.dump(result, yaml_file, sort_keys=False, indent=2, allow_unicode=True)

# 示例调用
csv_to_yaml("input.csv", "output.yaml")

关键修改说明

  • 引入依赖库:添加csv和yaml标准库导入,分别用于CSV读取和YAML生成
  • 表头处理优化:新增记录tests列索引的逻辑,为后续字段分割做准备
  • 字段转换逻辑:针对tests字段,用split("|")将字符串分割为列表,同时去除每个元素的前后空格
  • YAML格式控制:使用yaml.dump时设置sort_keys=False保持字段顺序与CSV一致,indent=2匹配期望的缩进格式
  • 完整封装:把逻辑封装为可复用函数,支持指定输入输出文件路径,完善文件IO的异常安全处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:24:31