YAML 是专门用来写配置文件的语言,非常简洁和强大,远比 JSON 格式方便。

   YAML在python语言中有PyYAML安装包。

  

   YAML 语言(发音 /ˈjæməl/ )的设计目标,就是方便人类读写。它实质上是一种通用的数据串行化格式。

    它的基本语法规则如下:

    1、大小写敏感

    2、使用缩进表示层级关系

    3、缩进时不允许使用Tab键,只允许使用空格。

    4、缩进的空格数目不重要,只要相同层级的元素左侧对齐即可

    5、# 表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释一样

 

    YAML 支持的数据结构有三种:

    1、对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)

    2、数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)

    3、纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期

 

1、环境搭建

  执行命令:pip  install pyyaml

  注意:我是在pycharm中的 terminal(终端)直接执行了命令,当然还可以在命令行执行命令安装。

  python 中读取yaml

  安装成功的效果,不报错!

  python 中读取yaml

 

2、Yaml 在Python中的使用

  新建一个yaml文件

  python 中读取yaml

 

 

3、代码实现获取配置文件信息

  

python 中读取yaml
# FileName : YamlDemo.py
# Author   : Adil
# DateTime : 2017/12/29 12:00
# SoftWare : PyCharm

import yaml
import os

# 获取当前文件路径 D:/WorkSpace/StudyPractice/Python_Yaml/YamlStudy
filePath = os.path.dirname(__file__)
print(filePath)
# 获取当前文件的Realpath  D:\WorkSpace\StudyPractice\Python_Yaml\YamlStudy\YamlDemo.py
fileNamePath = os.path.split(os.path.realpath(__file__))[0]
print(fileNamePath)
# 获取配置文件的路径 D:/WorkSpace/StudyPractice/Python_Yaml/YamlStudy\config.yaml
yamlPath = os.path.join(fileNamePath,'config.yaml')
print(yamlPath)
# 加上 ,encoding='utf-8',处理配置文件中含中文出现乱码的情况。
f = open(yamlPath,'r',encoding='utf-8')

cont = f.read()

x = yaml.load(cont)
print(type(x))
print(x)
print(x['EMAIL'])
print(type(x['EMAIL']))
print(x['EMAIL']['Smtp_Server'])
print(type(x['EMAIL']['Smtp_Server']))
print(x['DB'])
print(x['DB']['host'])

print(x.get('DB').get('host'))

print(type(x.get('DB')))
python 中读取yaml

 

打印输出结果如下:

python 中读取yaml

 

4、代码实现写入配置文件

 

python 中读取yaml
# 写入yaml 文件
# a 追加写入,w,覆盖写入
fw = open(yamlPath,'a',encoding='utf-8')
# 构建数据
data = {"cookie1":{'domain': '.yiyao.cc', 'expiry': 1521558688.480118, 'httpOnly': False, 'name': '_ui_', 'path': '/', 'secure': False, 'value': 'HSX9fJjjCIImOJoPUkv/QA=='}}
# 装载数据
yaml.dump(data,fw)
# 读取数据,获取文件
f = open(yamlPath,'r',encoding='utf-8')
# 读取文件
cont = f.read()
# 加载数据
x = yaml.load(cont)
# 打印数据
print(x)
# 打印读取写入的数据
print(x.get("cookie1"))
python 中读取yaml

 

写入效果如图

 

python 中读取yaml

 

自此基本完成了读取写入配置的操作,其实Yaml与configParser类似都是处理配置文件,下面附加地址,可以了解一哈

http://www.cnblogs.com/BlueSkyyj/p/7683820.html

 

 

 下面引用别人的例子,方便日后使用。

python 中读取yaml
#######################################字符串##############################################
#1、字符串默认不使用引号表示
str1: 这是一个字符串

#2、如果字符串之中包含空格或特殊字符,需要放在引号之中。
str2: '内容: *字符串'

#3、单引号和双引号都可以使用,双引号不会对特殊字符转义。
str3: '内容\n字符串'
str4: "content\n string"

#4、单引号之中如果还有单引号,必须连续使用两个单引号转义。
s3: 'labor''s day'

#5、字符串可以写成多行,从第二行开始,必须有一个单空格缩进。换行符会被转为空格
strline: 这是一段
  多行
  字符串
  
#6、多行字符串可以使用|保留换行符,也可以使用>折叠换行
this: |
  Foo
  Bar
that: >
  Foo
  Bar
  
#7、+表示保留文字块末尾的换行,-表示删除字符串末尾的换行。
s4: |
  Foo4
s5: |+
  Foo5
s6: |-
  Foo6
s7: |
  Foo7
python 中读取yaml

 

python 中读取yaml
###################################对象####################
#1、对象的一组键值对,使用冒号结构表示。
animal: pets  #{'animal': 'pets'}
#
##2、Yaml 也允许另一种写法,将所有键值对写成一个行内对象
dict1: { name: Steve, foo: bar } #{'dict1': {'foo': 'bar', 'name': 'Steve'}}
python 中读取yaml

 

python 中读取yaml
####################################数组###################

# 1、数组可以采用行内表示法。
animal: [Cat, Dog]

#{'animal': ['Cat', 'Dog']}

#2、一组连词线开头的行,构成一个数组。
animal1:
 - Cat
 - Dog
 - Goldfish

# {'animal1': ['Cat', 'Dog', 'Goldfish']}
python 中读取yaml

 

python 中读取yaml
############################复合结构##########################
#对象和数组可以结合使用,形成复合结构

languages:
 - Ruby
 - Perl
 - Python
websites:
 YAML: yaml.org
 Ruby: ruby-lang.org
 Python: python.org
 Perl: use.perl.org
#{'languages': ['Ruby', 'Perl', 'Python'], 'websites': {'Python': 'python.org', 'YAML': 'yaml.org', 'Ruby': 'ruby-lang.org', 'Perl': 'use.perl.org'}}

db:
    host: xxx
    port: 3306
    user: weibospider
    password: xxx
    db_name: weibo
    db_type: mysql

#{'db': {'host': 'xxx', 'db_name': 'weibo', 'user': 'weibospider', 'db_type': 'mysql', 'password': 'xxx', 'port': 3306}}
python 中读取yaml

 

python 中读取yaml
##########################纯量#############################
#1、数值直接以字面量的形式表示
number: 12.30 #{'number': 12.3}

#2、布尔值用true和false表示
isSet: true #{'isSet': True}
isSet1: false #{'isSet1': False}

3、null用~表示
parent: ~   #{'parent': None}

#4、时间采用 ISO8601 格式。
time1: 2001-12-14t21:59:43.10-05:00  #{'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000)}

##5、日期采用复合 iso8601 格式的年、月、日表示。
date: 2017-07-31  #{'date': datetime.date(2017, 7, 31)}

#6、YAML 允许使用两个感叹号,强制转换数据类型。
int_to_str: !!str 123  #{'bool_to_str': 'true'}
bool_to_str: !!str true #{'bool_to_str': 'true'}

分类:

技术点:

相关文章: