我想保存这本词典
data = { yaml: { l: 'hi\nif x = y:\n print z\n' } }
在YAML中使用Python。当我使用yaml.dump(data, default_flow_style=False)
时,输出为:
yaml:
l: "hi\nif x = y:\n print z\n"
但我知道YAML有这种格式:
yaml:
l:
|
hi
if x = y:
print z
如何以上述格式输出输出?
答案 0 :(得分:1)
尝试使用YAML标量:
import yaml
from collections import OrderedDict
class literal(str): pass
def literal_presenter(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(literal, literal_presenter)
def ordered_dict_presenter(dumper, data):
return dumper.represent_dict(data.items())
yaml.add_representer(OrderedDict, ordered_dict_presenter)
d_temp = OrderedDict(l=literal('hi\nif x = y:\n print z\n'))
d = OrderedDict(yaml=literal(yaml.dump(d_temp)))
print(yaml.dump(d))
<强>输出:强>
yaml: |
l: |
hi
if x = y:
print z
希望它适合你...