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

如何使用Python将.TXT文件中的数据转换为YAML格式?

Python实现特定格式文件转目标YAML格式

源文件格式

H|Column1|Column2|Column3|
    T|2022-07-01|00001|TEST 1|
    T|2022-07-01|00002|TEST 2|
    F | Record count |    2| | 

目标YAML格式

H: T
Column1: 2022-07-01
Column2: 00001
Column3: TEST 1
-
  H: T
  Column1: 2022-07-01
  Column2: 00002
  Column3: TEST 2

实现代码

import yaml

def convert_to_yaml(input_path, output_path):
    # 读取源文件内容
    with open(input_path, 'r', encoding='utf-8') as f:
        lines = [line.strip() for line in f if line.strip()]
    
    # 提取并处理表头
    header_raw = lines[0].strip('|')
    headers = [item.strip() for item in header_raw.split('|') if item.strip()]
    
    data = []
    # 遍历数据行(跳过表头和最后一行统计信息)
    for line in lines[1:-1]:
        line_clean = line.strip('|')
        fields = [item.strip() for item in line_clean.split('|') if item.strip()]
        # 表头与字段配对成字典
        data.append(dict(zip(headers, fields)))
    
    # 写入YAML文件
    with open(output_path, 'w', encoding='utf-8') as f:
        yaml.dump(
            data, 
            f, 
            sort_keys=False, 
            allow_unicode=True, 
            default_flow_style=False,
            indent=2
        )

# 替换为你的实际文件路径
convert_to_yaml("source_file.txt", "output.yaml")

代码说明

  1. 文件读取:先读取源文件,过滤掉空行并去除每行前后空白,减少后续处理干扰。
  2. 表头处理:提取第一行的表头内容,清理掉多余分隔符和空白,得到规整的表头列表。
  3. 数据转换:遍历中间的有效数据行,每行同样清理后分割字段,和表头一一配对成字典,存入数据列表。
  4. YAML生成:使用yaml.dump将数据列表转为YAML格式,通过参数保证字段顺序与表头一致、生成易读的层级结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:30:57