'How to update YAML file using PyYAML?

How can I comment the 'driverClassName' line and update org.quartz.threadPool.threadCount to 200

In the YAML snippet below, using python (PyYAML package)?

PRODUCT_HOME: /app
config: 
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
spring:
  quartz:
  job-store-type: jdbc
  enabled: true
  properties: 
     org.quartz.threadPool.threadCount: 50


Solution 1:[1]

PyYAML cannot add comments. It actually removes all comments on loading, so in general PyYAML is not the appropriate tool for YAML documents that need further human interaction (which I assume is the reason for adding a comment).

You should do this with ruamel.yaml (disclaimer: I am the author of that package):

import sys
import ruamel.yaml

yaml_str = """\
PRODUCT_HOME: /app
config: 
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
spring:
  quartz:
  job-store-type: jdbc
  enabled: true
  properties: 
     org.quartz.threadPool.threadCount: 50
"""
    
yaml = ruamel.yaml.YAML()
data = yaml.load(yaml_str)
data['config'].yaml_add_eol_comment('this is the SQL driver', 'driverClassName', column=50)
data['spring']['properties']['org.quartz.threadPool.threadCount'] = 200
yaml.dump(data, sys.stdout)

which gives:

PRODUCT_HOME: /app
config:
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver       # this is the SQL driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
spring:
  quartz:
  job-store-type: jdbc
  enabled: true
  properties:
    org.quartz.threadPool.threadCount: 200

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anthon