工作经验分享 - yaml
type: channel
link: https://www.xuehuafei.cn/tag/yaml/
items: python简单处理yml文件

python简单处理yml文件
type: item
date: 2022-08-13T21:50:00+08:00
description: YAML 是用于 Python 处理 yml 文件的 loader/dumper 程序包version:0.17.21更新日期2022-02-12文档说明http://yaml.readthedocs.iorepositoryhttps://sourceforge.net/projects/ruamel-yaml/pypihttps://pypi.org/project/ruamel.yaml/0.16.13版本是最后一个在 Python 2.7上测试的版本。0.17.21是最后一个在 Python 3.5上测试的版本，也是最后一个支持旧的 PyYAML 函数的版本，你必须创建一个YAML ()实例并使用它的.load()和.dump()方法。Examplesfrom ruamel.yaml import YAML inp = """\ # example name: # details family: Smith # very common given: Alice # one of the siblings """ yaml = YAML() code = yaml.load(inp) code['name']['given'] = 'Bob' yaml.dump(code, sys.stdout) # 输出结果 # example name: # details family: Smith # very common given: Bob # one of the sibling注意老版本的使用方式from __future__ import print_function import sys import ruamel.yaml inp = """\ # example name: # details family: Smith # very common given: Alice # one of the siblings """ code = ruamel.yaml.load(inp, ruamel.yaml.RoundTripLoader) code['name']['given'] = 'Bob' ruamel.yaml.dump(code, sys.stdout, Dumper=ruamel.yaml.RoundTripDumper) # the last statement can be done less efficient in time and memory with # leaving out the end='' would cause a double newline at the end # print(ruamel.yaml.dump(code, Dumper=ruamel.yaml.RoundTripDumper), end='') # 输入结果 name: # details family: Smith # very common given: Bob # one of the siblings访问方式可以通过[]和get，访问ruamel.yaml.dump()返回的数据格式。修改方式通过构造dict，将值添加到指定的位置，并且可以添加注释import sys from ruamel.yaml import YAML yaml_str = """\ first_name: Art occupation: Architect # This is an occupation comment about: Art Vandelay is a fictional character that George invents... """ yaml = YAML() data = yaml.load(yaml_str) data.insert(1, 'last name', 'Vandelay', comment="new key") yaml.dump(data, sys.stdout) # 返回结果---------------------- irst_name: Art last name: Vandelay # new key occupation: Architect # This is an occupation comment about: Art Vandelay is a fictional character that George invents...默认情况下ruamel.yaml 缩进俩个空格，用于表示键值对和列表，可以通过例如使用 yaml.indent() 来更改此默认缩进。YMLYAML 是 "YAML Ain't a Markup Language"（YAML 不…