使用 python 读取 yaml 文件

使用前安装 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

这里写图片描述

你可能感兴趣的:(Python基础)