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

Python使用yaml.dump写入YAML文件时出现外层多余引号如何解决

问题原因

你对yaml.dump做了两次重复调用:

  1. 第一次调用yaml.dump已经把DataFrame转成的字典序列化为了标准YAML格式的字符串,存到了text变量中
  2. 第二次写文件时你又把这个已经是YAML格式的字符串作为参数传给了yaml.dump,此时PyYAML会把整个字符串当做普通字符串值来序列化,自然就会在外层加引号,同时把字符串里的换行符转义成\n,就出现了你遇到的错误输出。
修复方案

有两种常用修复方式,选任意一种即可:

方案1:直接写入已经生成的YAML字符串

把写文件部分的代码替换为直接写字符串即可,不需要再次序列化:

""" Export the recently converted yml to getData.yml """
with open('getData.yml', 'w') as outfile:
    outfile.write(text)

方案2:省略提前序列化步骤,直接把字典写入YAML

你也可以不需要提前生成text变量,直接在写文件时做序列化:

import csv
import pandas
import yaml

""" Reading whole csv file with panda library """
df = pandas.read_csv('chord-progressions.csv')

""" Export the converted yml to getData.yml """
with open('getData.yml', 'w') as outfile:
    yaml.dump(
        df.to_dict(orient='records'),
        outfile,
        sort_keys=False, 
        width=72, 
        indent=4,
        default_flow_style=False
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:45:02