使用 python 讀取 yaml 檔案
阿新 • • 發佈:2019-01-05
使用前安裝 PyYaml 包
read_yaml.yaml
first_name: 111
second_name: 222
third_name: 333
basic_name:
test_name: 444
selected_name:
- 666
- 777
read_yaml.py
# -*- coding:utf-8 -*- import os import yaml current_path = os.path.abspath(os.path.dirname(__file__)) print(current_path) print(current_path + '/../test_dir') with open(current_path + '/../test_dir/' + 'read_yaml.yaml', 'r') as f: temp = yaml.load(f.read()) print(temp) print(temp['basic_name']) print(temp['basic_name']['test_name']) print(temp['basic_name']['selected_name'][0])
輸出:
C:\Users\rHotD\Documents\GitHub\fieldwork_test\2017-06-01 C:\Users\rHotD\Documents\GitHub\fieldwork_test\2017-06-01/../test_dir {'third_name': 333, 'basic_name': {'selected_name': [666, 777], 'test_name': 444}, 'first_name': 111, 'second_name': 222} {'selected_name': [666, 777], 'test_name': 444} 444 666 Process finished with exit code 0