美文网首页python 高级模块
学习笔记-Python PyYAML模块

学习笔记-Python PyYAML模块

作者: sofiiii | 来源:发表于2018-12-12 15:26 被阅读0次

1.YAML简介

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

2.基本语法规则

  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格。
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • #表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释一样

3.支持的数据结构

  • 字符串
#######################################字符串##############################################
#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
  • 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
####################################数组###################

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

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

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

# {'animal1': ['Cat', 'Dog', 'Goldfish']}
  • 纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期
##########################纯量#############################
#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'}
  • 复合结构
#对象和数组可以结合使用,形成复合结构

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}}
  • 分段
#test.yaml
---
name: James
age: 20
---
name: Lily
age: 19
# -*- coding: utf-8 -*-
import yaml
 
ys = yaml.load_all(file('test.yaml', 'r'))
for y in ys:
    print y

输出:

{'age': 20, 'name': 'James'}
{'age': 19, 'name': 'Lily'}
  • 示例
# test.yaml
#这个例子输出一个字典,其中value包括所有基本类型
str: "Hello World!"
int: 110
float: 3.141
boolean: true  # or false
None: null  # 也可以用 ~ 号来表示 null
time: 2016-09-22t11:43:30.20+08:00  # ISO8601,写法百度
date: 2016-09-22  # 同样ISO8601

输出:

{'date': datetime.date(2016, 9, 22), 'None': None, 'boolean': True, 'str': 'Hello World!', 'time': datetime.datetime(2016, 9, 22, 3, 43, 30, 200000), 'int': 110, 'float': 3.141}

4.PyYAML模块安装

pip install PyYAML

5.Python使用yaml

#yaml文本
house:
  family:
    name: Doe
    parents:
      - John
      - Jane
  address:
    number: 34
    street: Main Street
import yaml
f = open('example.ini',encoding="utf-8")
x = yaml.load(f)
print(x)
print("---------")

aproject = {'name': 'Silenthand Olleander',
            'race': 'Human',
            'traits': ['ONE_HAND', 'ONE_EYE']
            }
ret = yaml.dump(aproject)
print(ret)


aproject = ["a","b","c"]
ret = yaml.dump(aproject)
print(ret)

aproject = ("a","b","c")
ret = yaml.dump(aproject)
print(ret)

aproject = {"a":1,"b":2}
ret = yaml.dump(aproject)
print(ret)

输出

E:\python\python_sdk\python.exe E:/python/py_pro/5.configparse.py
{'house': {'family': {'name': 'Doe', 'parents': ['John', 'Jane']}, 'address': {'number': 34, 'street': 'Main Street'}}}
---------
name: Silenthand Olleander
race: Human
traits: [ONE_HAND, ONE_EYE]

[a, b, c]

[a, b, c]

{a: 1, b: 2}

相关文章

网友评论

    本文标题:学习笔记-Python PyYAML模块

    本文链接:https://www.haomeiwen.com/subject/odsuhqtx.html