yaml 通常用来存储数据,类似于json
安装:pip install ruamel.yaml
建一个空的yaml文件
写入数据
import os
from ruamel import yaml
# 将字典写入到yaml
data = {
'host1': '123',
'host2': 456,
'host3': {'asd': '123'},
'host4': [12, '234', ['wer', 234]],
'host5': {'asd': '123', 'eee': [12, '234', ['wer', 234]]}
}
curpath = os.path.dirname(os.path.realpath(__file__)) # 当前脚本路径
yamlpath = os.path.join(curpath, "config.yaml") # 在当前脚本路径中,找到config.yaml文件
# 写入到yaml文件
with open(yamlpath, "w", encoding="utf-8") as f:
yaml.dump(data, f, Dumper=yaml.RoundTripDumper)
读取yaml文件
import os
from ruamel import yaml
curpath = os.path.dirname(os.path.realpath(__file__)) # 当前脚本路径
yamlpath = os.path.join(curpath, "config.yaml") # 在当前脚本路径中,找到config.yaml文件
# 读取yaml文件
data = yaml.load(open(yamlpath, "r").read(), Loader=yaml.Loader)
print(data)
print(data['host4'][1])
封装起来以后好调用
from ruamel import yaml
class Yaml():
''' yaml文件的读和写 '''
def write_yaml(self, yamlPath, data):
''' 往yaml里面写入数据 '''
try:
with open(yamlPath, "w", encoding="utf-8") as f:
yaml.dump(data, f, Dumper=yaml.RoundTripDumper)
return True
except Exception as error:
print(f'yaml文件写入失败,错误如下:\n{error}')
return False
def read_yaml(self, yamlPath):
''' 读取yaml里面里面的数据'''
try:
data = yaml.load(open(yamlPath, "r").read(), Loader=yaml.Loader)
return data
except Exception as error:
print(f'读取yaml失败,错误如下:{error}')
return False
if __name__=="__main__":
import os
wryaml = Yaml()
curpath = os.path.dirname(os.path.realpath(__file__)) # 当前脚本路径
yamlpath = os.path.join(curpath, "config.yaml") # 在当前脚本路径中,找到config.yaml文件
# 写入数据文件
data = {
'AAA': 111,
'BBB': 222
}
print(wryaml.write_yaml(yamlpath, data))
# 读取数据文件
print(wryaml.read_yaml(yamlpath)['AAA'])