Python 之PyYAML模塊

一、安裝模塊:PyYAMLpython

二、語法:mysql

下載地址:http://pyyaml.org/download/pyyaml/PyYAML-3.12.tar.gzsql

   官網: http://www.yaml.orgmongodb

已有配置文件config.yaml:url

# 配置文件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'

讀取文件內容以下:ip

{'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'}}utf-8

讀取:get

# -*- 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

運行結果:it

[{'port': 26379, 'ip': 'localhost'}]
{'url': 'mysql+mysqlconnector://xinxin:123456@localhost/test'}
mysql+mysqlconnector://xinxin:123456@localhost/testio

寫入:

# -*- 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]
相關文章
相關標籤/搜索