python-9-yaml文件的操作

# pip install pyyaml -i https://pypi.douban.com/simple/
# pip install Template

1. yaml文件的读取

import yaml
def read_yaml(file):
    with open(file, "r", encoding="utf-8") as file:
        data = yaml.load(stream=file, Loader=yaml.FullLoader)  # 读取yaml文件
        return data

2. yaml文件的写入

def write_yaml(file, data):
    with open(file, "w", encoding="utf-8") as file:
        yaml.dump(data=data, stream=file, allow_unicode=True)

3. yaml文件的修改

Template: 字符串模板,用于替换字符串中的变量
Template 中主要的俩种格式:
# 1:$variable 使用 $变量名 引用变量

# 2:${variable} 使用 ${变量名} 大括号包起来

from string import Template

def update_yaml(file, data):
    with open(file, "r", encoding="utf-8") as files:
        read_yaml_str = files.read()  # 读取文件
        t = Template(read_yaml_str) # 绑定读取的数据
        c = t.safe_substitute(data)  # 字符串替换模板
        print("c=", c)
        print(type(c))

        x = yaml.safe_load(c)  # 转换成python数据
        print("x=", x)
        for i in x:
            print(i)
        print(type(x))


if __name__ == '__main__':
    update_yaml("../data/1.yaml", {"site": "321","user":"123"})

4. 修改

def modify_yaml_file(file_path, key, value):
    with open(file_path, 'r') as f:
      data = yaml.load(f, Loader=yaml.FullLoader)
      data[key] = value

    with open(file path, w') as f:
       yaml.dump(data,f)
posted @ 2023-01-31 10:37  测试圈的彭于晏  阅读(58)  评论(0)    收藏  举报