python参数化之读取写⼊yaml⽂件
最近⾃动化测试参数化使⽤了yaml⽂件进⾏存放,简单记录读取和写⼊操作
1.读取如下yaml⽂件中的具体value值代码如下spring怎么读取yaml
#测试环境IP、端⼝
host: localhost:8080
---
#仿真环境IP、端⼝
host: localhost:8081
def filePath(fileDir, fileName):
return os.path.join(
os.path.dirname(os.path.dirname(__file__)), fileDir, fileName)
def readYaml(filePath):
with open(filePath, 'r', encoding='utf-8') as f:
return list(yaml.safe_load_all(f))
fileDir = 'config'
file = 'config.yaml'
data = readYaml(filePath(fileDir, file))
print(data[0]['host'])  # 打印结果为:localhost:8080
2.写⼊操作,常⽤作上个操作返回的值将其写⼊yaml⽂件,供后⾯操作读取使⽤,yaml⽂件及参考代码如下:
def set_state(docNumber, key, value):
file_name = "test.yaml"
with open(file_name, 'r', encoding="utf-8") as f:
doc = list(yaml.safe_load_all(f))  # 将类型转换为list类型
# print(list(doc))
doc[docNumber][key] = value
with open(file_name, 'w', encoding="utf-8") as f:
yaml.safe_dump_all(doc, f, default_flow_style=False)
set_state(value='122.123.124.125:8888',
docNumber=1,
key='host')   
执⾏后的结果为:
host: localhost:8080
---
host: 122.123.124.125:8888
注意:yaml⽂档由“---”分隔,如果任何流(例如⽂件)包含多个⽂档,则应使⽤yaml.safe_load_all函数,⽽不是yaml.safe_load;写⼊⾮“---”分隔的⽂档时,使⽤yaml.safe_load、yaml.safe_dump即可,同时不需要转换类型;参考代码如下:
def set_state(key, value):
file_name = "test.yaml"
with open(file_name, 'r', encoding="utf-8") as f:
doc = yaml.safe_load(f)
doc[key] = value
with open(file_name, 'w', encoding="utf-8") as f:
yaml.safe_dump(doc, f, default_flow_style=False)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。