[英]How to add contents to YAML file using ruamel.yaml?
Here is the input.yml file这是 input.yml 文件
PRODUCT_HOME: /app
config:
active-profiles: mysql,oauth2
driverClassName: com.mysql.cj.jdbc.Driver
datasourceurl: jdbc:h2:file:./data
datasourceuser: sa
server:
error:
path: /error
whitelabel:
enabled: false
port: 8080
Output file should look like: Output 文件应如下所示:
PRODUCT_HOME: /app
config:
active-profiles: mysql,oauth2
driverClassName: com.mysql.cj.jdbc.Driver
datasourceurl: jdbc:h2:file:./data
datasourceuser: sa
server:
error:
path: /error
whitelabel:
enabled: false
port: 8080
servlet:
session:
cookie:
secure: true
How can I achieve this using Python (ruamel.yaml) package?如何使用 Python (ruamel.yaml) package 实现此目的?
You should create the correct data structure for the data you want to add and then add that datastructure to the mapping that is the value of server
您应该为要添加的数据创建正确的数据结构,然后将该数据结构添加到作为server
值的映射
import sys
import ruamel.yaml
from pathlib import Path
in_file = Path('input.yaml')
nd = dict(servlet=dict(session=dict(cookie=dict(secure=True))))
yaml = ruamel.yaml.YAML()
data = yaml.load(in_file)
data['server'].update(nd)
# print(data)
yaml.dump(data, sys.stdout)
which gives:这使:
PRODUCT_HOME: /app
config:
active-profiles: mysql,oauth2
driverClassName: com.mysql.cj.jdbc.Driver
datasourceurl: jdbc:h2:file:./data
datasourceuser: sa
server:
error:
path: /error
whitelabel:
enabled: false
port: 8080
servlet:
session:
cookie:
secure: true
Alternatively, if you have the data to add as YAML input you can load that and then update:或者,如果您有要添加为 YAML 输入的数据,您可以加载它然后更新:
yaml_str = """
servlet:
session:
cookie:
secure: true
"""
yaml = ruamel.yaml.YAML()
nd = yaml.load(yaml_str)
data = yaml.load(in_file)
data['server'].update(nd)
# print(data)
yaml.dump(data, sys.stdout)
which also gives:这也给出了:
PRODUCT_HOME: /app
config:
active-profiles: mysql,oauth2
driverClassName: com.mysql.cj.jdbc.Driver
datasourceurl: jdbc:h2:file:./data
datasourceuser: sa
server:
error:
path: /error
whitelabel:
enabled: false
port: 8080
servlet:
session:
cookie:
secure: true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.