小编omi*_*248的帖子

PyYAML 中的数组没有缩进或空格

在下面的代码中,我创建了net_plan_dict变量字典并将其转换为 YAML 格式文件。在字典中,我有一个名为的字段addresses,它是一个由三个元素组成的数组。创建 YAML 文件后,三个数组元素未放置在该addresses字段下:

import yaml

net_plan_dict = {
    'networking': {
        'addresses': ['192.168.1.1', '192.168.1.2', "192.168.1.3"],
        'gateway4': '192.168.121.1'
    }
}

with open("new.yaml", "w") as f:
    yaml.dump(net_plan_dict, f)

Run Code Online (Sandbox Code Playgroud)

上述代码的输出如下(在下面的文件中,IP不在地址下方,并且没有空格或缩进)。

新的.yaml:

networking:
  addresses:
  - 192.168.1.1 <-------- does not have indent
  - 192.168.1.2
  - 192.168.1.3
  gateway4: 192.168.121.1


Run Code Online (Sandbox Code Playgroud)

但我的目标是获取此输出文件(当 ips 位于地址字段下时如何创建此文件):

networking:
  addresses:
    - 192.168.1.1
    - 192.168.1.2
    - 192.168.1.3
  gateway4: 192.168.121.1

Run Code Online (Sandbox Code Playgroud)

python pyyaml python-3.x

6
推荐指数
1
解决办法
3249
查看次数

标签 统计

python ×1

python-3.x ×1

pyyaml ×1