1、安装模块:PyYAML
2、语法:
下载地址:http://pyyaml.org/download/pyyaml/PyYAML-3.12.tar.gz
已有配置文件config.yaml:
# 配置文件config.yaml cache: - {ip: 'localhost', port: 26379} database: url: 'mysql+mysqlconnector://xinxin:123456@localhost/test' connection: glados: 'mongodb://xinxin#123456@127.0.0.1/test'
读取文件内容如下:
{'database': {'url': 'mysql+mysqlconnector://xinxin:123456@localhost/test'}, 'cache': [{'ip': 'localhost', 'port': 26379}], 'safety': {'secret': 'asingo5l86jigncu', 'white_list': ['127.0.0.1', '::1', '119.168.1.101', '119.168.1.102', '119.168.1.103']}, 'connection': {'glados': 'mongodb://xinxin#123456@127.0.0.1/test'}}
读取:
# -*- coding: utf-8 -*- import yaml # 导入模块 import os config_path = 'E:/xinxin/learn_python' config = yaml.load(open(os.path.join(config_path, 'config.yaml'), encoding='utf8')) # 加载文件 print(config) # 读取文件所有内容 print(config['cache']) # 获取cache print(config['database']) # 获取database print(config['database']['url']) # 获取databese的url
运行结果:
[{'port': 26379, 'ip': 'localhost'}]
{'url': 'mysql+mysqlconnector://xinxin:123456@localhost/test'}
mysql+mysqlconnector://xinxin:123456@localhost/test
写入:
# -*- coding: utf-8 -*- import yaml # 导入模块 import os config_path = 'E:/xinxin/learn_python' f = open(os.path.join(config_path, 'config.yaml'), 'w', encoding='utf8') # r, w, a 分别是读,写,追加模式 print(f) data = {'safety': {'white_list': ['127.0.0.1', '::1', '192.168.1.101', '192.168.1.102', '192.168.1.103'], 'secret': 'asingo5l86jigncu'}} yaml.dump(data, f) f.close()
运行结果:
safety: secret: asingo5l86jigncu white_list: [127.0.0.1, '::1', 192.168.1.101, 192.168.1.102, 192.168.1.103]