python接口自動化測試二十九:yaml配置文件的寫和讀(ruamel.yaml)


 
        

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])

 

封裝起來以后好調用

import os
from ruamel import yaml


class WRYaml:
""" yaml文件的讀和寫 """

def __init__(self):
""" 指定yaml文件的路徑 """
self.configpath = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'config')

def read_yaml(self, yaml_file='conf.yaml'):
""" 讀取yaml里面里面的數據"""
try:
with open(os.path.join(self.configpath, yaml_file), "r", encoding='utf8') as f:
return yaml.load(f, Loader=yaml.Loader)
except Exception as error:
print(f'讀取yaml失敗,錯誤如下:{error}')
return False

def write_yaml(self, data, yaml_file='conf.yaml', mode='w'):
""" 往yaml里面寫入數據
yamlFile:yaml文件名
data:要寫入的數據
mode:寫入方式: w,覆蓋寫入, a,追加寫入
將原數據讀取出來,如果沒有要加入的key,則創建一個,如果有,則執行key下面的數據修改
"""
try:
old_data = self.read_yaml(yaml_file) or {}
for data_key, data_value in data.items():
if not old_data.get(data_key):
old_data.setdefault(data_key, {})
for value_key, value_value in data_value.items():
old_data[data_key][value_key] = value_value
with open(os.path.join(self.configpath, yaml_file), mode, encoding="utf-8") as f:
yaml.dump(old_data, f, Dumper=yaml.RoundTripDumper)
return True
except Exception as error:
print(f'yaml文件寫入失敗,錯誤如下:\n{error}')
return False


if __name__ == "__main__":
wryaml = WRYaml()
# 寫入數據文件
data = {
'test': {'AAA': 134511, 'BBB': 333}
}
print(wryaml.write_yaml(yaml_file='conf.yaml', data=data))
# 讀取數據文件
print(wryaml.read_yaml('conf.yaml'))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM