如何在没有 ruamel.yaml 的情况下为 Python YAML 转储中的项目添加双引号?

How can I add double quotes to items in a Python YAML dump without ruamel.yaml?

我正在为需要双引号字符串选项列表的服务生成配置文件。我想避免按照此 中的建议通过 pip3 -r requirements.txt 安装其他软件包,并使用 python 3.8.10ubuntu 20.04 上提供的 yaml 模块。我想要一种解决此问题的方法,而无需搜索行并替换它们。

Python 3.8.10 (default, Sep 28 2021, 16:10:42)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
>>> yaml.__file__
'/usr/lib/python3/dist-packages/yaml/__init__.py'

python3 test.yaml

import yaml

configDict = {}
configDict["OptionList"] = [
        "\"item1/Enable\"",
        "\"item2/Disable\""
    ]

with open('./testConfig.yaml', 'w') as f:
    yaml.dump(configDict, f)

testConfig.yaml

当前输出:

OptionList:
- '"item1/Enable"'
- '"item2/Disable"'

期望的输出:

OptionList:
- "item1/Enable"
- "item2/Disable"

它需要深入研究文档和源代码,看看是否有更改它的选项。

此时我会简单地获取 text 并使用 replace()

import yaml

configDict = {
    "OptionList": [
        'item1/Enable',
        'item2/Disable'
    ]
}

text = yaml.dump(configDict)
print(text)

text = text.replace("'\"", '"').replace("\"'", '"')
print(text)

with open('./testConfig.yaml', 'w') as f:
    f.write(text)

结果:

OptionList:
- '"item1/Enable"'
- '"item2/Disable"'

OptionList:
- "item1/Enable"
- "item2/Disable"

如果我使用 default_style='"' 那么我会得到 " "

中的所有值
import yaml

configDict = {
    "OptionList": [
        'item1/Enable',
        'item2/Disable'
    ]
}

text = yaml.dump(configDict, default_style='"')
print(text)

结果:

"OptionList":
- "item1/Enable"
- "item2/Disable"