如何使用python将字符串列表以github操作的格式写入yaml文件

2024-04-23 17:53:40 发布

您现在位置:Python中文网/ 问答频道 /正文

python yaml包(版本5.1.2)能够正确加载以下文件,即使列表不是用前导-编写的

xx: [x1, x2]
yy: [y1, y2, y3]

加载代码如下所示

import yaml

with open('some file') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)

此格式在github操作配置yaml文件中使用。比如说,

on: [push, pull_request]

jobs:
  build:

    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: [2.7, 3.5, 3.6, 3.7, 3.8]
        os: [ubuntu-16.04, ubuntu-18.04]
        node: [6, 8, 10]

但是,当我使用yaml.dump(data, f)data写入文件时,它采用-约定,即

xx:
- x1
- x2
yy:
- y1
- y2
- y3

有没有一种方法可以将其强制到github操作中,比如格式化

有人告诉我default_flow_style,但它并没有给出我想要的东西

yaml.dump({"A":[1,2,3],"B":[4,5,6]},default_flow_style=True)

输出为'{A: [1, 2, 3], B: [4, 5, 6]}\n'


Tags: 文件githubdefaultyamldataonubuntudump
2条回答

正如@Tsyvarev所指出的,我想要的行为可以通过

yaml.dump({"A":[1,2,3],"B":[4,5,6]}, default_flow_style=None)

虽然official documentation似乎没有定义这个None行为:

By default, PyYAML chooses the style of a collection depending on whether it has nested collections. If a collection has nested collections, it will be assigned the block style. Otherwise it will have the flow style.

If you want collections to be always serialized in the block style, set the parameter default_flow_style of dump() to False.

一般来说,不可能完全按照加载YAML时的编写方式来编写YAML,请参见this question

您可以按照答案中的建议进行操作:加载到节点图而不是本地对象。在Pyaml中看起来是这样的:

import yaml
import io

input = """
xx: [x1, x2]
yy: [y1, y2, y3]
"""

loader = yaml.Loader(input)
node = loader.get_single_node()

stream = io.StringIO()
dumper = yaml.Dumper(stream)
dumper.open()
dumper.serialize(node)
dumper.close()
print(stream.getvalue())

输出将是:

xx: [x1, x2]
yy: [y1, y2, y3]

这是因为节点仍然记得其原始样式(而本机数据不记得)。仍然可以修改YAML结构,但是现在需要将数据创建为节点,而不是仅仅操纵加载的Python数据

如果要使用Python创建数据并以首选格式转储,最简单的方法可能是:

  • 创建数据
  • 将其转储到YAML字符串
  • 将该字符串作为节点图加载
  • 遍历节点图并根据自己的喜好更改节点的style属性
  • 再次将节点图表示为YAML

相关问题 更多 >