Python 自动化处理 Yaml 文件

1. Yaml 是什么

  • Yaml是一种简洁的非标记语言。

  • Yaml是一个可读性高,用来表达数据序列化的格式。

  • Yaml以数据为中心,使用空白,缩进,分行组织数据,从而使得表示更加简洁。

  • Yaml特别适合用来表达或编辑数据结构、各种配置文件、文件大纲等。

2. Yaml 文件规则

  • 区分大小写;

  • 注释标识为#;

  • 使用缩进表示层级关系;

  • 使用空格键缩进,而非Tab键;

  • 缩进的空格数目不固定,只需要相同层级的元素左侧对齐;

  • 文件中的字符串不需要使用引号标注,但若字符串包含有特殊字符则需用引号标注;

3. Yaml 文件数据结构

Yaml文件内容—示例1:

China:
  family:
    name: Smile_Family
    parents:
      - John
      - Jane
    children:
      - Lily
      - Frank
  address:
    province: BeiJing
    region: chaoyang
    city: BeiJing

Yaml文件内容—示例2:

China:
  family: { name: Smile_Family, parents: [John, Jane], children: [Lily, Frank] }
  address: { province: BeiJing, region: chaoyang, city: BeiJing }

从上述示例文件内容可以看到 Yaml 数据结构:

1). 对象:键值对的集合(简称 "映射或字典")

例如:family 和 address 这两个对象后面分别有对应的键值对集合。

2). 键值对用冒号 “:” 结构表示,冒号与值之间需用空格分隔

例如:

family 对象中的 key 为 name 与其对应的 value 值 Smile_Family 之间是使用空格分隔的。

address 对象中的 key 为 province 与其对应的 value 值 BeiJing 之间是使用空格分隔的。

3). 数组:一组按序排列的值(简称 "序列或列表"),数组前加有 “-” 符号,符号与值之间需用空格分隔

例如:

parents 中的 John 和 Jane

children 中的 Lily 和 Frank

4). 纯量(scalars):单个的、不可再分的值。例如:字符串、bool值、整数、浮点数、时间、日期、null等

None值可用null也可用 ~ 表示;

4. 安装与导入

python -m pip install pyyaml
import yaml

5. Yaml数据示例

5.1 Yaml 转 Python 列表

yaml文件内容如下:

-tony
-22
-tester

Python解析输出为:

['tony',22,'tester']

5.2 Yaml 转 Python 字典

这个例子输出一个字典,其中value包括所有基本类型

Yaml文件内容如下:

str: "Hello World!"
int: 110
float: 3.141
boolean: true  # or false
None: null  # 也可以用 ~ 号来表示 null
time: 2016-09-22t11:43:30.20+08:00  # ISO8601,写法百度
date: 2016-09-22  # 同样ISO8601

Python解析输出为:

{'str': 'Hello World!', 'int': 110, 'float': 3.141, 'boolean': True, 'None': None, 'time': datetime.datetime(2016, 9, 22, 3, 43, 30, 200000), 'date': datetime.date(2016, 9, 22)}

5.3 Yaml 转 Python 列表嵌套字典

Yaml文件内容如下:

- name: jack
  age: 0
  job: test
- name: tony
  age: 30

Python输出为:

[{'name': 'jack', 'age': 0, 'job': 'test'}, {'name': 'tony', 'age': 30}]

5.4 特殊字符的说明

如果字符串没有空格或特殊字符,不需要加引号,但如果其中有空格或特殊字符,则需要加引号。

这里要注意单引号和双引号的区别:

单引号中的特殊字符转到 Python 会被转义,也就是到最后是原样输出;

双引号不会被 Python 转义,到最后是输出了特殊字符;

Yaml文件内容如下:

str0: hi
str1: "Hello World"
str2: "Hello\nWorld"

Python输出:

{'str': 'hi', 'str1': 'Hello World', 'str2': 'Hello\nWorld'}

6. Python代码实现

import yaml

class TestYaml:
    def __init__(self,yamlFile):
        '''初始化yaml文件'''
        self.yamlFile=yamlFile

    def readYaml(self):
        '''读取yaml文件'''
        with open(self.yamlFile,'r',encoding="utf-8") as f:
            values=yaml.load(f,Loader=yaml.FullLoader)
            print(values)

    def writeYaml(self,dict):
        '''写yaml文件'''
        with open(self.yamlFile,'a',encoding="utf-8") as f:
            try:
                yaml.dump(data=dict,stream=f,encoding="utf-8",allow_unicode=True)
            except Exception as e:
                print(e)

    def cleanYaml(self):
        '''清空yaml文件'''
        with open(self.yamlFile,'w') as f:
            f.truncate()


if __name__ == '__main__':
    ty=TestYaml("testyaml.yaml")
    ty.readYaml()

    dict1={"jobs":{"computers":"tester"},"age":22}
    ty.writeYaml(dict1)
    ty.readYaml()

    ty.cleanYaml()
    ty.readYaml()

欢迎关注【无量测试之道】公众号,回复【领取资源】

Python+Unittest框架API自动化、

Python+Unittest框架API自动化、

Python+Pytest框架API自动化、

Python+Pandas+Pyecharts大数据分析、

Python+Selenium框架Web的UI自动化、

Python+Appium框架APP的UI自动化、

Python编程学习资源干货、

Vue前端组件化框架开发、

资源和代码 免费送啦~
文章下方有公众号二维码,可直接微信扫一扫关注即可。

备注:我的个人公众号已正式开通,致力于IT互联网技术的分享。

包含:数据分析、大数据、机器学习、测试开发、API接口自动化、测试运维、UI自动化、性能测试、代码检测、编程技术等。

微信搜索公众号:“无量测试之道”,或扫描下方二维码:

  在这里插入图片描述

 添加关注,让我们一起共同成长!

猜你喜欢

转载自blog.csdn.net/weixin_41754309/article/details/125295128