如何在YAML文件中打印Python中没有字符串的[]

时间:2015-05-11 04:10:41

标签: python yaml pyyaml

在我的山药文件中,我正在尝试这个

with open(fname, "w") as f:
     yaml.safe_dump({'items':['test', 'test2']}, f,
                    default_flow_style=False, width=50, indent=4)

以下列格式打印

items:
- 'test'
- 'test2'

我希望输出格式如下

items: ['test', 'test2']

我该怎么做?

编辑:

这是我的完整代码

   d = {}        
   for m in ['B1', 'B2', 'B3']:
                d2 = {}
                for f in ['A1', 'A2', 'A3']:
                    # here i don't want any flow style
                    d2[f] = ['test', 'test2']
                d[m] = d2

    with open(fname, "w") as f:
        yaml.safe_dump(d, f, default_flow_style=True, width=50, indent=8)

2 个答案:

答案 0 :(得分:2)

暂时不要default_flow_style=Falsedoes the complete opposite of what you want

>>> import yaml
>>> yaml.safe_dump({'items': ['test', 'test2']}, default_flow_style=False)
'items:\n- test\n- test2\n'
>>> yaml.safe_dump({'items': ['test', 'test2']})
'items: [test, test2]\n'

对于部分文档格式,您可以使用自定义representers,例如:

class Items(list):
    pass


def items_representer(dumper, data):
    return dumper.represent_sequence('tag:yaml.org,2002:seq', data, flow_style=True)


yaml.representer.SafeRepresenter.add_representer(Items, items_representer)

result = yaml.safe_dump({
    'items': Items(['test', 'test2']),
    'other list': ['1', '2'],
}, default_flow_style=False)

# items: [test, test2]
# other list:
# - '1'
# - '2'
print(result)

答案 1 :(得分:2)

如果您想要精确控制并且只有具有流式的特定列表,则应使用ruamel.yaml(这是我的PyYAML增强版):

import ruamel.yaml
from ruamel.yaml.comments import CommentedSeq

d = {}
for m in ['B1', 'B2', 'B3']:
    d2 = {}
    for f in ['A1', 'A2', 'A3']:
        # here i don't want any flow style
        d2[f] = CommentedSeq(['test', 'test2'])
        if f != 'A2':
            d2[f].fa.set_flow_style()
    d[m] = d2

x = ruamel.yaml.dump(
    d, Dumper=ruamel.yaml.RoundTripDumper,
    default_flow_style=False, width=50, indent=8)
print(x)

会给你:

B1:
        A1: [test, test2]
        A3: [test, test2]
        A2:
        - test
        - test2
B2:
        A1: [test, test2]
        A3: [test, test2]
        A2:
        - test
        - test2
B3:
        A1: [test, test2]
        A3: [test, test2]
        A2:
        - test
        - test2

CommentedSeq的行为与普通的Python列表相似,但允许您指定注释,设置流/块样式等。

在往返YAML时,

ruamel.yaml通常用于保留注释,元素的流/块样式等。即如果你愿意追加:

d2 = ruamel.yaml.load(x, Loader=ruamel.yaml.RoundTripLoader)
y = ruamel.yaml.dump(
    d2, Dumper=ruamel.yaml.RoundTripDumper, width=50, indent=8)
assert x == y

断言成立。

但它当然可以用来从头开始生成YAML。你可以,例如也可以使用CommentedMap类型并保持dict / mapping的键顺序。