Reputation: 11
I have a yaml doc as follows.
doc="""
... network-interface: >
... auto $(intf)
... iface $(intf) inet static
... address $(addr)
... network $(net)
... netmask $(mask)
... """
I am loading this doc and getting a python dict. I am trying to convert this doc back to my original doc and I am getting '\n
' characters.
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"
How do I get the original doc back without the '\n
'.
Upvotes: 1
Views: 1425
Reputation: 76598
You specify the string with the folded block style, but your extra indent on the line starting with 'iface` and following cause it get 'hard' newlines.
If you align those lines:
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
you will get:
{network-interface: 'auto $(intf) iface $(intf) inet static address $(addr) network
$(net) netmask $(mask)
'}
If you want your output YAML to be more closely like your input, you should consider using ruamel.yaml (of which I am the author) and use the 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
gives you:
network-interface: |
auto $(intf)
iface $(intf) inet static
address $(addr)
network $(net)
netmask $(mask)
Upvotes: 1