pip install ruamel.yaml
读取:
from ruamel.yaml import YAML
from pathlib import Path
# default, if not specfied, is 'rt' (round-trip)
yaml = YAML(typ='safe')
# 参数doc是 an object that has the .read() method, a string or a pathlib.Path()
data = yaml.load(Path("test_out.yaml"))
print(data)
data2 = yaml.load("""a:
b: 2
c: 3
""")
print(data2)
写入:
from ruamel.yaml import YAML
from pathlib import Path
yaml = YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
def tr(s):
return s.replace('
', '<
') # such output is not valid YAML!
# 可以传入一个处理字符串的函数,来处理需要输出的yaml文件中的内容
yaml.dump({'a': [1, 2]}, Path("test_out.yaml"), transform=tr)
修改:
a:
- 1
- 2
b:
name: jim
from pathlib import Path
import ruamel.yaml
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
data = yaml.load(Path("test_out.yaml"))
# 新增
data['a'].append({"b": 18})
data['a'].append(18)
# 给a中列表第一个值添加注释
data['a'].yaml_add_eol_comment('comment 4', 0) # takes column of comment 1
# 给b中指定的字段添加注释
data['b'].yaml_add_eol_comment('comment 5', 'name') # takes column of comment 2
# column=10 指定注释的离行首的距离
data['a'].yaml_add_eol_comment('comment 7', 1, column=10)
yaml.dump(data, Path("test.yaml"))
from ruamel.yaml import YAML
from pathlib import Path
yaml_str = """
first_name: Art
middle name:
Vandelay: 18
occupation: Architect # This is an occupation comment
about: Art Vandelay is a fictional character that George invents...
"""
yaml = YAML()
data = yaml.load(yaml_str)
print(data)
data.insert(1, 'last name', {'Vandelay': 18})
yaml.indent(mapping=2, sequence=4, offset=2)
yaml.dump(data, Path('test.yaml'))
---分隔
a:
- 1
- 2
b:
name: jim
---
c:
- 1
- 2
from pathlib import Path
import ruamel.yaml
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
data = yaml.load_all(Path("test_out.yaml"))
print(list(data))