读取yaml文件,修改yml文件的值

目的:

        把 B_yml 中的 url 替换成,A_yaml 中的 url。

代码:

此方法并不通用,想要通用,可自行修改成方法、类的使用。

import yaml
import re

A_path = "A.yaml"
B_path = "B.yml"
data = ''
with open(A_path, "r", encoding="utf-8") as f:
    # yaml文件转成字典,取到需要的数据
    A_url = yaml.load(f, Loader=yaml.FullLoader)["platformversion"]["url"]
print("A_url:%s"%A_url)

# yml文件转成字典
with open(B_path, 'rb')as f:
    res = yaml.load(f, Loader=yaml.FullLoader)
datasource_url = res["spring"]["datasource"]["url"]
B_url = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", datasource_url)[0]
print("B_url:%s"%B_url)
datasource_url = datasource_url.replace(B_url, A_url)
# 变更
res["spring"]["datasource"]["url"] = datasource_url
res["spring"]["redis"]["host"] = A_url

# 写入
with open(B_path, 'w', encoding='utf-8') as f:
    res = yaml.dump(res, f, allow_unicode=True)

A.yaml

osversion:
  centos: 'centos-release-7-7.1908.0.el7.centos.x86_64'
  os: 'Linux master-196 3.10.0-862.el7.x86_64 GNU/Linux'
  docker: 18.09.7,
platformversion:
  iotserver: '1.3'
  iotweb: '8'
  iotactivemq: latest
  iotinfluxdb: latest
  iotredis: '3.2'
  iotmysql: '5.7'
  url:  '111.11.1.1'
  path : 'eeee'
  netmask :

B.yml

files:
  path: ${file-path:d:/files}
logging:
  config: classpath:logback-admin.xml
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    password: qizhi025
    url: jdbc:mysql://222.22.2.2:3306/qzxl_iot?useUnicode=true&xxx&useSSL=false
    username: root
  redis:
    host: 222.22.2.2
    port: 6379
    timeout: 10s
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB
token:
  expire:
    seconds: 7200
  jwtSecret: xxx

修改后
 

files:
  path: ${file-path:d:/files}
logging:
  config: classpath:logback-admin.xml
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    password: qizhi025
    url: jdbc:mysql://111.11.1.1:3306/qzxl_iot?useUnicode=true&xxx&useSSL=false
    username: root
  redis:
    host: 111.11.1.1
    port: 6379
    timeout: 10s
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB
token:
  expire:
    seconds: 7200
  jwtSecret: xxx

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值