python读取、修改yaml文件

简述

YAML(YAML Ain't Markup Language)是一种用于表示数据序列化的文本格式,具有简洁易读的特点。它旨在成为人类友好的数据交互格式,并可被多种编程语言解析和生成。

YAML 文件常用于配置文件、数据序列化、API调用和存储结构化数据等场景。它被广泛应用于各种编程语言和工具中,并与 JSON、XML 等格式相比,更具可读性和人类友好性。

import os
import yaml.scanner


class GetYamlData:
    """ 获取 yaml 文件中的数据 """

    def __init__(self, file_dir):
        self.file_dir = str(file_dir) 

    def get_yaml_data(self) -> dict:
        """
        获取 yaml 中的数据
        :param: fileDir:
        :return:
        """
        # 判断文件是否存在
        if os.path.exists(self.file_dir):
            data = open(self.file_dir, 'r', encoding='utf-8')
            res = yaml.load(data, Loader=yaml.FullLoader)
            data.close()
        else:
            raise FileNotFoundError("文件路径不存在")
        return res

    def write_yaml_data(self, key: str, value) -> int:
        """
        更改 yaml 文件中的值, 并且保留注释内容
        :param key: 字典的key
        :param value: 写入的值
        :return:
        """
        with open(self.file_dir, 'r', encoding='utf-8') as file:
            # 创建了一个空列表,里面没有元素
            lines = []
            for line in file.readlines():
                # if line != '\n':
                lines.append(line)
            file.close()

        with open(self.file_dir, 'w', encoding='utf-8') as file:
            flag = 0
            for line in lines:
                # line 为空格则跳过
                if not line: 
                    continue
                left_str = line.split(":")[0]
                if key == left_str.lstrip() and '#' not in line:
                    newline = f"{left_str}: {value}"
                    line = newline
                    file.write(f'{line}\n')
                    flag = 1
                else:
                    file.write(f'{line}')
            file.close()
            return flag

测试yaml文件

# 商品信息
- name: Apple
  price: 2.5
  quantity: 10
  is_available: true
  categories:
    - fruits
    - organic

- name: Laptop
  price: 1000
  quantity: 5
  is_available: false
  categories:
    - electronics

 执行结果

[{'name': 'Apple', 'price': 2.5, 'quantity': 10, 'is_available': True, 'categories': ['fruits', 'organic']}, {'name': 'Laptop', 'price': 1000, 'quantity': 5, 'is_available': False, 'categories': ['electronics']}]

- 表示列表,文件结构是缩进表示 

测试文件2 

# 配置文件
server:
  host: example.com
  port: 8080
  timeout: 30

database:
  name: mydb
  username: admin
  password: 123456

执行结果

{'server': {'host': 'example.com', 'port': 8080, 'timeout': 30}, 'database': {'name': 'mydb', 'username': 'admin', 'password': 123456}}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值