yaml參數管理器
這是文件目錄關系,其中config存放.yaml文件,scripts存放py文件
然后就可以自由使用了:
import yaml
import os#獲取路徑
script_directory = os.path.dirname(os.path.abspath(__file__))
# 相對于腳本文件的路徑
image_relative_path = "../config/1.yaml"# 構建文件的完整路徑
path = os.path.join(script_directory, image_relative_path)try:with open(path, 'r') as file:yaml_data = yaml.load(file, Loader=yaml.FullLoader)except FileNotFoundError:print("ControlParameter.yaml 文件不存在")print(yaml_data['k2'])
除了手動寫入yaml外,還可以在程序中書寫:
寫入YAML文件的方法
def write_yaml(yaml_path,data):with open(yaml_path, encoding="utf-8", mode="w") as f:yaml.dump(data,stream=f,allow_unicode=True)a = 10data = {'name': 'John Doe','age': 30,'pa': a,'city': 'New York'
} # 字典是單引號的write_yaml(path, data)
yaml本身就是一個字典,所以可以適當使用提高我們的效率。