Python - 通过PyYaml库操作YAML文件

PyYaml简单介绍

  • Python的PyYAML模块是Python的YAML解析器和生成器
  • 它有个版本分水岭,就是5.1

 

读取YAML5.1之前的读取方法

def read_yaml(self, path):
    with open(path, encoding="utf-8") as f:
        result = f.read()
        result = yaml.load(result)
        return result

当你运行的时候,会报一个Warning

 

读取YAML 5.1之后的读取方法

因为在5.1之后,直接用load()已经过时了,需要在方法里面加一个 loader 的请求参数,如下:

def read_yaml(self, path):
    with open(path, encoding="utf-8") as f:
         result = f.read()
         result = yaml.load(result, Loader=yaml.FullLoader) #loader可选择BaseLoader、SafeLoader、FullLoader、UnsafeLoader
         return result

也可以,根据Python语法糖转换,如下:

def read_yaml(self, path):
    with open(path, encoding="utf-8") as f:
        result = f.read()
        result = yaml.full_load(result)
        return result

针对不同的需要,加载器有如下几种类型:

  1. BaseLoader:仅加载最基本的YAML
  2. SafeLoader:安全地加载YAML语言的子集。建议用于加载不受信任的输入。(safe_load)
  3. FullLoader:加载完整的YAML语言。避免任意代码执行。这是当前(PyYAML 5.1)默认加载器调用 yaml.load(input) (发出警告后)(full_load)
  4. UnsafeLoader(也称为Loader向后兼容性):原始的Loader代码,可以通过不受信任的数据输入轻松利用。(unsafe_load) 

 

存储数据到YAML的方法

with open(path, "w", encoding="utf-8") as f:
     yaml.dump(data, f, Dumper=yaml.SafeDumper) # 可选BaseDumper、SafeDumper 

 

 封装成一个操作YAML的工具类

class YamlUtil:
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            print("YamlUtil first init")
            cls.__instance = super(YamlUtil, cls).__new__(cls, *args, **kwargs)
        return cls.__instance

    def read_yaml(self, path):
        with open(path, encoding="utf-8") as f:
            result = f.read()
            result = yaml.load(result, Loader=yaml.FullLoader)
            return result

    def write_yaml(self, path, data):
        with open(path, "w", encoding="utf-8") as f:
            yaml.dump(data, f, Dumper=yaml.SafeDumper)

yamlUtil = YamlUtil()

 

posted @ 2020-03-13 13:54  小菠萝测试笔记  阅读(1983)  评论(0编辑  收藏  举报