如何yaml转储带有'\ n'的python dict来输出纯文本

时间:2015-04-14 07:20:51

标签: python yaml dump

我有一个yaml doc如下。

 doc="""
... network-interface: >
...    auto $(intf)
...       iface $(intf) inet static
...       address $(addr)
...       network $(net)
...       netmask $(mask)
... """

我正在加载这个doc并获得一个python dict。我正在尝试将此文档转换回原始文档,但我收到的是“\n”字符。

ydict = yaml.load(doc)
ndoc  = yaml.dump(ydict)
print ndoc
{network-interface: "auto $(intf)\n   iface $(intf) inet static\n   address $(addr)\n\
    \   network $(net)\n   netmask $(mask)\n"}

print yaml.dump(ydict, default_flow_style=False)
network-interface: "auto $(intf)\n   iface $(intf) inet static\n   address $(addr)\n\
  \   network $(net)\n   netmask $(mask)\n"

如何在没有“\n”的情况下收回原始文档。

1 个答案:

答案 0 :(得分:1)

您使用folded block style指定字符串,但是在' iface`开头的行中额外缩进并导致它变得难以接受'换行。

如果您对齐这些行:

import yaml

doc="""
network-interface: >
      auto $(intf)
      iface $(intf) inet static
      address $(addr)
      network $(net)
      netmask $(mask)
"""

ydict = ruamel.yaml.load(doc, Loader=ruamel.yaml.RoundTripLoader)
ndoc  = ruamel.yaml.dump(ydict, Dumper=ruamel.yaml.RoundTripDumper)
ydict = ruamel.yaml.load(doc)
ndoc  = ruamel.yaml.dump(ydict)

print ndoc

你会得到:

{network-interface: 'auto $(intf) iface $(intf) inet static address $(addr) network
    $(net) netmask $(mask)

    '}

如果您希望输出YAML更接近您的输入,则应考虑使用ruamel.yaml(我是作者)并使用literal style|):

import ruamel.yaml

doc="""
network-interface: |
      auto $(intf)
      iface $(intf) inet static
      address $(addr)
      network $(net)
      netmask $(mask)
"""

ydict = ruamel.yaml.load(doc, Loader=ruamel.yaml.RoundTripLoader)
ndoc  = ruamel.yaml.dump(ydict, Dumper=ruamel.yaml.RoundTripDumper)

print ndoc

给你:

network-interface: |
  auto $(intf)
  iface $(intf) inet static
  address $(addr)
  network $(net)
  netmask $(mask)