简述
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}}