yaml文件内容

websites:
YAML: yaml.org
Ruby: ruby-lang.org
Python: python.org
versions:
- version2:
name: 2.x
- version3: 3.x
Perl: use.perl.org

python代码

import yaml
import os

def yamltest():
# ('/home/zxl/PycharmProjects/pythonProject', 'pyyamltest.py')
fileNamePath = os.path.split(os.path.realpath(__file__))[0]
print(os.path.split(os.path.realpath(__file__)))
yamlPath = os.path.join(fileNamePath, 'test.yaml')
f = open(yamlPath, 'r', encoding='utf-8')
cont = f.read()
x = yaml.load(cont)
# print(type(x))
print(x['websites'])
print(x['websites']['YAML'])
print(x['websites']['Ruby'])
print(type(x['websites']['versions'][0]['version2']['name']))

if __name__=='__main__':
yamltest()

运行结果

python pyyaml模块使用示例:读取yaml文件内容_ruby