python基础-PyYaml操作yaml文件

yaml语法

格式


它的基本语法规则如下 
大小写敏感 
使用缩进表示层级关系 
缩进时不允许使用Tab键,只允许使用空格。 
缩进的空格数目不重要,只要相同层级的元素左侧对齐即可

YAML 支持的数据结构有三种 
1、对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary) 
2、数组:一组按次序排列的值,又称为序列(sequence) / 列表(list) 
3、纯量(scalars):单个的、不可再分的值

对象的一组键值对,使用冒号结构表示。

animal: pets

#或者如下格式
hash: { name: Steve, foo: bar }
  • 1
  • 2
  • 3
  • 4

数组

- Cat
- Dog
- Goldfish #或者如下格式 animal: [Cat, Dog]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

复合结构

languages:
 - Ruby
 - Perl
 - Python 
websites:
 YAML: yaml.org 
 Ruby: ruby-lang.org 
 Python: python.org Perl: use.perl.org 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

纯量纯量是最基本的、不可再分的值

        字符串
        布尔值
        整数
        浮点数
        Null
        时间
        日期

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

字符串:以下是5种表现格式

str: 这是一行字符串
str: '内容: 字符串'
s1: '内容\n字符串' s2: "内容\n字符串" str: 'labor''s day' 
  • 1
  • 2
  • 3
  • 4
  • 5

yaml2种写法

我们来看一个完整的yaml配置文件

数据结构可以用类似大纲的缩排方式呈现,结构通过缩进来表示,连续的项目通过减号“-”来表示,map结构里面的key/value对用冒号“:”来分隔。样例如下:

house:
  family:
    name: Doe
    parents:
      - John
      - Jane
    children:
      - Paul - Mark - Simone address: number: 34 street: Main Street city: Nowheretown zipcode: 12345
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

YAML也有用来描述好几行相同结构的数据的缩写语法,数组用’[]’包括起来,hash用’{}’来包括。因此,上面的这个YAML能够缩写成这样:

house:
  family: { name: Doe, parents: [John, Jane], children: [Paul, Mark, Simone] } address: { number: 34, street: Main Street, city: Nowheretown, zipcode: 12345 }
  • 1
  • 2
  • 3

安装PyYaml

下载地址https://github.com/yaml/pyyaml 
然后将其lib3\yaml包,放在python安装包lib包下,然后命令行监测是否安装成功即可 
这里写图片描述

扫描二维码关注公众号,回复: 2061947 查看本文章

python使用yaml

我们初始化一个yaml配置文件

house:
  family:
    name: Doe
    parents:
      - John
      - Jane
  address:
    number: 34
    street: Main Street
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
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) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

输出内容如下:

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} Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/nkwy2012/p/9291740.html