![](/img/trans.png)
[英]How can I preserve or add quotes around values in a YAML file without stripping comments as a side effect using ruamel.yaml?
[英]How can I add double quotes to items in a Python YAML dump without ruamel.yaml?
我正在為需要雙引號字符串選項列表的服務生成配置文件。 我想避免按照此答案中的建議通過pip3 -r requirements.txt
安裝其他軟件包,並使用 Z1D41C853AF58D3A7AEZ54900CE29417D8 上的ubuntu 20.04
python 3.8.10
隨附的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
當前 output:
OptionList:
- '"item1/Enable"'
- '"item2/Disable"'
所需的 output:
OptionList:
- "item1/Enable"
- "item2/Disable"
它需要挖掘文檔和源代碼以查看是否可以選擇更改它。
此時我將簡單地獲取text
並使用replace()
import yaml
configDict = {}
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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.