Python脚本 yaml文件和properties文件互转
config.yaml
# 配置项目启动端口号
server:
port: 9090
# 开启调试模式
debug: true
# 配置数据连接信息
spring:
datasource:
url: jdbc:mysql://127.0.0.0:3306/dbname?characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
sets:
- 1
- 2
- 3
config.properties
# 配置项目启动端口号
server.port=8088
# 开启调试模式
debug=true
# 配置数据连接信息
spring.datasource.url=jdbc:mysql://127.0.0.0:3306/dbname?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
convert.py
import yaml
properties = []
# dfs
def travel(root: dict, path: str):
if not isinstance(root, dict):
# remove key last .
k = path.strip(".")
# yaml list
if isinstance(root, list):
# join list turned one line
properties.append({k: ",".join([str(x) for x in root])})
else:
properties.append({k: root})
return
for key in root.keys():
travel(root[key], path + key + ".")
# yaml file convert to properties file
def yaml2properties():
with open("config.yml", "r") as f:
lines = f.read()
result = yaml.safe_load(lines)
print(result)
travel(result, "")
for property in properties:
for key, value in property.items():
print(f"{key}={value}")
def properties2yaml():
tree = {}
with open("config.properties", "r") as f:
for line in f.readlines():
if line.startswith("#"):
continue
else:
parts = line.split("=", 2)
key, value = parts[0], parts[1]
nodes = key.split(".")
length = len(nodes)
if length >= 2:
temp = tree
for node in nodes[0 : length - 1]:
temp[node] = {}
temp = temp[node]
last = nodes[length - 1]
# set value
temp[last] = value.strip()
else:
tree[nodes[0]] = value.strip()
return tree
if __name__ == "__main__":
tree = properties2yaml()
yml = yaml.dump(tree)
print(yml)