python读取yaml配置文件
支持多种语言:python、js、golang、java、c、c++
YAML 语言(发音 /ˈjæməl/ )的设计目标,就是方便人类读写。它实质上是一种通用的数据串行化格式。
它的基本语法规则如下。
- 大小写敏感
- 使用缩进表示层级关系
- 缩进时不允许使用Tab键,只允许使用空格。
- 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
#
表示注释,从这个字符一直到行尾,都会被解析器忽略。
YAML 支持的数据结构有三种。
- 对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
- 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
- 纯量(scalars):单个的、不可再分的值
安装插件:
pip install pyyaml
PyYAML文档:https://pyyaml.org/
https://pyyaml.org/wiki/PyYAMLDocumentation
yaml配置文件结构
网上搜搜吧,很多
python操作yaml文件:
https://www.cnblogs.com/BlueSkyyj/p/8143826.html
读取配置:
import yaml import os # 获取当前文件路径 D:/WorkSpace/StudyPractice/Python_Yaml/YamlStudy filePath = os.path.dirname(__file__) print(filePath) # 获取当前文件的Realpath D:\WorkSpace\StudyPractice\Python_Yaml\YamlStudy\YamlDemo.py fileNamePath = os.path.split(os.path.realpath(__file__))[0] print(fileNamePath) # 获取配置文件的路径 D:/WorkSpace/StudyPractice/Python_Yaml/YamlStudy\config.yaml yamlPath = os.path.join(fileNamePath,'config.yaml') print(yamlPath) # 加上 ,encoding='utf-8',处理配置文件中含中文出现乱码的情况。 f = open(yamlPath,'r',encoding='utf-8') cont = f.read() x = yaml.load(cont) print(type(x)) print(x) print(x['EMAIL']) print(type(x['EMAIL'])) print(x['EMAIL']['Smtp_Server']) print(type(x['EMAIL']['Smtp_Server'])) print(x['DB']) print(x['DB']['host']) print(x.get('DB').get('host')) print(type(x.get('DB')))
写入配置
# 写入yaml 文件 # a 追加写入,w,覆盖写入 fw = open(yamlPath,'a',encoding='utf-8') # 构建数据 data = {"cookie1":{'domain': '.yiyao.cc', 'expiry': 1521558688.480118, 'httpOnly': False, 'name': '_ui_', 'path': '/', 'secure': False, 'value': 'HSX9fJjjCIImOJoPUkv/QA=='}} # 装载数据 yaml.dump(data,fw) # 读取数据,获取文件 f = open(yamlPath,'r',encoding='utf-8') # 读取文件 cont = f.read() # 加载数据 x = yaml.load(cont) # 打印数据 print(x) # 打印读取写入的数据 print(x.get("cookie1"))
参考:
https://yaml.org/
http://www.ruanyifeng.com/blog/2016/07/yaml.html