python基礎-PyYaml操做yaml文件

yaml語法

格式


它的基本語法規則以下 
大小寫敏感 
使用縮進表示層級關係 
縮進時不容許使用Tab鍵,只容許使用空格。 
縮進的空格數目不重要,只要相同層級的元素左側對齊便可css

YAML 支持的數據結構有三種 
一、對象:鍵值對的集合,又稱爲映射(mapping)/ 哈希(hashes) / 字典(dictionary) 
二、數組:一組按次序排列的值,又稱爲序列(sequence) / 列表(list) 
三、純量(scalars):單個的、不可再分的值python

對象的一組鍵值對,使用冒號結構表示。git

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

數組github

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

複合結構web

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種表現格式ruby

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

yaml2種寫法

咱們來看一個完整的yaml配置文件數據結構

數據結構能夠用相似大綱的縮排方式呈現,結構經過縮進來表示,連續的項目經過減號「-」來表示,map結構裏面的key/value對用冒號「:」來分隔。樣例以下:app

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可以縮寫成這樣:spa

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包下,而後命令行監測是否安裝成功便可 
這裏寫圖片描述

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