Skip to main content
 首页 » 编程设计

python3之就地编辑 YAML 文件中的值

2025年02月15日12fff_TT

我正在尝试使用 PyYAML 和 Python3 来编辑 YAML 文件中的值(这是一个 Hiera 数据结构,但这有点离题)。

使用 yaml.safe_load 和 yaml.dump 很容易实现。我遇到的问题是我需要保留注释、空格、顺序和其他格式。也就是说,当我编辑给定键的值时,这应该是文件中的唯一更改。 (不需要自己添加或删除 key 。)

在我的例子中,这些是二级 key 。我可以用正则表达式或某种形式的状态机来做到这一点 - 但它非常讨厌。有人知道已经巧妙地做到这一点的库吗?

这是有关 YAML 的虚拟示例:

--- 
# Some form of comment block. 
# Some form of comment block. 
# Some form of comment block. 
 
# This is my config block. 
config::me: 
  key0: 123 
  key1: 456 
 
# This is another config block: 
applications: 
  frontend: 
    version: '2.4.2' 
    enabled: true 
  backend: 
    version: '4.3.9' 
    enabled: false 
 
# More comments etcetera. 

基本上我需要做的是定位 applications.frontent.version 并将值从 2.4.2 更新为 2.4.3 而不触及文件中的任何内容。

请您参考如下方法:

您可以为此使用 ruamel.yaml,它是 PyYAML ¹ 的衍生物。它是专门为执行这种往返、保留注释和原始文件中的其他一些事情而创建的,大多数解析器在往返过程中都会丢弃这些东西(它也是 YAML 1.2 兼容的,而 PyYAML 支持 1.1)

import sys 
import ruamel.yaml 
from ruamel.yaml.util import load_yaml_guess_indent 
from ruamel.yaml.scalarstring import SingleQuotedScalarString 
 
ys = """\ 
--- 
# Some form of comment block. 
# Some form of comment block. 
# Some form of comment block. 
 
# This is my config block. 
config::me: 
  key0: 123 
  key1: 456 
 
# This is another config block: 
applications: 
  frontend: 
    version: '2.4.2' 
    enabled: true 
  backend: 
    version: '4.3.9' 
    enabled: false 
 
# More comments etcetera. 
""" 
 
data, indent, block_seq_indent = load_yaml_guess_indent(ys, preserve_quotes=True) 
data['applications']['frontend']['version'] = SingleQuotedScalarString('2.4.3') 
ruamel.yaml.round_trip_dump(data, sys.stdout, explicit_start=True) 

给你:

--- 
# Some form of comment block. 
# Some form of comment block. 
# Some form of comment block. 
 
# This is my config block. 
config::me: 
  key0: 123 
  key1: 456 
 
# This is another config block: 
applications: 
  frontend: 
    version: '2.4.3' 
    enabled: true 
  backend: 
    version: '4.3.9' 
    enabled: false 
 
# More comments etcetera. 

preserve_quotes 选项和 SingleQuotedScalarString() 的使用是必需的,因为您在标量 2.4.3 和 周围有引号4.3.9 是多余的,通常会被删除。


¹ 免责声明:我是 ruamel.yaml 的作者。