如何使用 ruamel.yaml 向 YAML 文件添加内容?

How to add contents to YAML file using ruamel.yaml?

这是 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

输出文件应如下所示:

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

如何使用 Python (ruamel.yaml) 包实现此目的?

您应该为要添加的数据创建正确的数据结构 然后将该数据结构添加到作为 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)

给出:

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

或者,如果您有要添加为 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)

这也给出了:

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