yaml文件处理-Python篇

在自动化测试数据存储中,比较常见的有csv、json、excel文件等,另外一个非常简单、好用的,而且更简洁的文件,那就是咱们今天的主角yaml文件。

yaml

yaml文件遵循规则

  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • 使用#进行注释,从这个字符一直到行尾,都会被解析器忽略

pip安装Yaml

1
2
3
pip install pyyaml
# ruamel.yaml是pyyaml的衍生版,可以支持YAML类型文件最新版本
pip install ruamel.yaml

Code Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import yaml
import os

# test.yaml 文件在当前的文件的子目录 static 下
# 获取当前脚本所在文件夹路径
curPath = os.path.dirname(os.path.realpath(__file__))
# 获取yaml文件路径
yamlFile = os.path.join(curPath, "static/test.yaml")
def get_dict():
'''
读取数据
'''
with open(yamlFile, 'r', encoding='utf-8') as f:
d = yaml.load(f.read(), Loader=yaml.FullLoader)
return d

def repair_data(key, data):
'''
更新、追加操作
'''
with open(yamlFile, encoding='utf-8') as f:
dict_temp = yaml.load(f, Loader=yaml.FullLoader)
try:
dict_temp[key] = data
except:
if not dict_temp:
dict_temp = {}
dict_temp.update({key:data})
with open(yamlFile, 'w', encoding='utf-8') as f:
yaml.dump(dict_temp, f, allow_unicode=True) # allow_unicode=True,解决存储时unicode编码问题。

if __name__ == '__main__':
repair_data('key', "value")
print(get_dict())

yaml文件处理-Python篇
https://skynetboys.github.io/2023/09/24/yaml文件处理-Python篇/
Author
Edison
Posted on
September 24, 2023
Licensed under