yaml文件的操作

`1.写入yaml文件内容

import yaml

apiData = {
   "page": 1,
   "msg": "地址",
   "data": [{
      "id": 1,
      "name": "学校"
   }, {
      "id": 2,
      "name": "公寓"
   }, {
      "id": 3,
      "name": "流动人口社区"
   }],
}

# sort_keys=False字段表示不改变原数据的排序
# allow_unicode=True 允许写入中文,必须以字节码格式写入

with open("config.yaml","w",encoding="utf-8") as fs:
    yaml.dump(data=apiData,stream=fs,sort_keys=False,allow_unicode=True)

2.读取yaml数据

        config1.yaml文件内容

- config:
    name: apitest
    request:
        base_url: http://10.20.xx.xx:9999/api/private/v1/login
- test:
    name: 登录成功
    request:
        url: /get
        method: GET
    validate:
        - eq: [status_code,200]
import yaml
with open("config1.yaml",encoding="utf-8") as fs:
    content = yaml.load(fs.read(),yaml.FullLoader)

print(content)

# 结果:[{'config': {'name': 'apitest', 'request': {'base_url': 'http://10.20.43.78:9999/api/private/v1/login'}}}, {'test': {'name': '登录成功', 'request': {'url': '/get', 'method': 'GET'}, 'validate': [{'eq': ['status_code', 200]}]}}]

3.修改或者给yaml添加内容

思路:先读在写

import yaml

# 先读取内容

with open("config.yaml",encoding="utf-8") as fs:
    content = yaml.load(fs.read(),yaml.FullLoader)


# 修改对象后,再将其写入

for i in content['data']:
    i['sex'] ='男323'

# print(content)

with open("config.yaml","w",encoding="utf-8") as fs:
    yaml.dump(data=content,stream=fs,sort_keys=False,allow_unicode=True)

你可能感兴趣的