Python使用yaml.dump写入YAML文件时出现外层多余引号如何解决
问题原因
你对yaml.dump做了两次重复调用:
- 第一次调用
yaml.dump已经把DataFrame转成的字典序列化为了标准YAML格式的字符串,存到了text变量中 - 第二次写文件时你又把这个已经是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
相关产品推荐
相关产品推荐

