Python读写yaml文件

目录

1.关于yaml

yaml基本语法规则:

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

2.yaml数据结构

YAML 支持的数据结构有三种:

  • 对象

键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
对象的一组键值对,使用冒号结构表示。

  • 数组

一组按次序排列的值,又称为序列(sequence) / 列表(list)
一组连词线开头的行,构成一个数组。

  • 纯量(scalars

单个的、不可再分的值
包括字符串,布尔值,整数,浮点数,Null,时间,日期

3.yaml文件格式

auth.login:
  data:
    name: \'18888888883\'
    password: jnyj123456
  url: https://XXXX-api-XXXX.zje.com/auth/login
headers:
  Accept: \'*/*\'
  Accept-Encoding: gzip, deflate, br
  Accept-Language: zh-CN,zh;q=0.9
  Connection: keep-alive
  Content-Length: \'46\'
  Content-type: application/json
  Host: dexin-api-test.zje.com
  Origin: https://XXXX-spa-XXX.zje.com
  Referer: https://XXXX-spa-XXX.zje.com/
  Sec-Fetch-Dest: empty
  Sec-Fetch-Mode: cors
  Sec-Fetch-Site: same-site
  User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML,
    like Gecko) Chrome/98.0.4758.80 Safari/537.36
  authorization: Bearer
  sec-ch-ua: \'\" Not A;Brand\";v=\"33\"
  sec-ch-ua-mobile: ?0000
  sec-ch-ua-platform: macOSis

学习产出:

class OpenYaml(object):

    def __init__(self):
        self.file_path = os.path.join(route(\"/DataYaml/yaml.yaml\"))  # 拼接读取的文件路径

    def open(self, *args):
        \'\'\'
           args[0]: 字典名称
           args[1]: 字段值
           读取文件
        \'\'\'
        try:
            if len(args) == 2:  # 根据传值判断执行内容
                with open(self.file_path, \"r\") as f:  # 读取yaml
                    Json = f.read()  # 获取yaml
                    Dict = yaml.safe_load(Json)[args[0]]  # 提取制定内容
                if args[1] in Dict.keys():  # 判断key是否存在
                    logs.info(f\"yaml文件,查找内容成功,内容:{Dict[args[1]]}\")
                    return Dict[args[1]]
                else:
                    print(f\"对应字段{args[1]}不存在...\")
                    logs.info(f\"对应字段{args[1]}不存在...\")
            else:
                with open(self.file_path, \"r\") as f:
                    Json = f.read()
                    Dict = yaml.safe_load(Json)[args[0]]
                return Dict
        except Exception as e:
            print(f\'读取yaml文件,报错:{e}\')
            logs.info(f\'读取yaml文件,报错:{e}\')

    def Wri_file(self, *args):

        \'\'\'
        :param args: args[0] 接口字段、args[1] key、 args[2] value
        :return: None
        把字段写入yaml
        \'\'\'
        try:
            with open(self.file_path, encoding=\"utf-8\") as f:  # 读取文件
                data = yaml.load(f.read(), Loader=yaml.FullLoader)  # 获取读取内容
            print(data[args[0]])
            if data is not None:  # 判断读取内容是否为空
                if str(data[args[0]][args[1]]) in str(data[args[0]]):  # 判断name是否存在在dict
                    data[args[0]][args[1]] = args[2]
                    with open(self.file_path, \'w\', encoding=\"utf-8\") as f:  # 写入
                        yaml.dump(data, stream=f, allow_unicode=True)
                else:
                    print(\"写入文件的字段不存在!写入失败...\")
            else:
                logs.info(\"写入文件的返回值为空!不能写入...\")
        except Exception as y:
            logs.info(f\"写入文件失败:{y}\")


if __name__ == \"__main__\":
    OpenYaml().Wri_file(\"headers\", \"Content-Length\", \"22\")
    OpenYaml().open(\"auth.login\", \"data\")
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容