从0开始python学习-37.pytest中yaml的读写删除方法

目录

1. 写入

1.1 直接写入,会清空历史的文件内容

1.2 参数化写入,且使用追加的形式

2. 读取

3. 清空

3.1 使用write清空

3.2 使用f.truncate()方法清空


1. 写入

1.1 直接写入,会清空历史的文件内容

def writer_yaml(yaml_path):
    with open(yaml_path,encoding="utf-8",mode="w") as f:
        yaml.safe_dump({"data":[{"ces1":'123'},{"ces2":2}]},stream=f,allow_unicode=True)

1.2 参数化写入,且使用追加的形式

data = {"data2":[{"ces3":'444'},{"ces4":222}]}

def writer2_yaml(yaml_path,data):
    with open(yaml_path,encoding="utf-8",mode="a") as f:
        yaml.safe_dump(data,stream=f,allow_unicode=True)

2. 读取

def read_yaml(yaml_path): 
    with open(yaml_path,encoding="utf-8") as f:
        value = yaml.load(f,Loader=yaml.FullLoader)
        return value 

读取到刚才写入的内容为:

{'data5': [{'ces1': '123'}, {'ces2': 2}], 'data2': [{'ces3': '444'}, {'ces4': 222}]}

3. 清空

3.1 使用write清空

def clear_yaml(yaml_path):
    with open(yaml_path,encoding="utf-8",mode="w") as f:
        pass

3.2 使用f.truncate()方法清空

def clear_yaml(yaml_path):
    with open(yaml_path,encoding="utf-8",mode="w") as f:
        f.truncate()

 

你可能感兴趣的:(python,python,学习,开发语言,pytest)