01 python基礎——python解析yaml類型檔案

來源:互聯網
上載者:User

標籤:日期格   ssh   tab鍵   window   匯入   try   root   字元   install   

目錄

[TOC]

一、yaml介紹

        yaml全稱Yet Another Markup Language(另一種標記語言)。採用yaml作為設定檔,檔案看起來直觀、簡潔、方便理解。yaml檔案可以解析字典列表和一些基本變數的資料結構。

1.1 yaml文法規則
  1. 大小寫敏感
  2. 使用縮排展示層級關係
  3. 縮排時不允許使用tab鍵,只可以使用空格
  4. 縮排時空格數目不重要,只要相同元素左側對其即可
  5. # 表示當行注釋

    1.2 yaml環境搭建
    -- 安裝pip之後,執行以下操作pip install pyyaml
二、yaml檔案格式2.1 字典
# 普通字典key1:value# 嵌套字典key2:    sub_key1:value1    sub_keys:value2
2.2 列表
# 下面同級的para1、para2以及para3在同一列表中- para1- para2- para3
2.3 普通變數

        yaml設定檔,可以解析數字字串布爾類型資料、時間日期格式,也可以對數字、布爾類型資料做強制轉換,使其在解析成為字串類型的資料

2.3.1 yaml之None的表示方法
# 在yaml中~表示None~
2.3.2 yaml強制轉換資料類型
# 在yaml配置中,!!str data表示把資料data強制轉換為str類型age: !!str 18
2.3.3 yaml日期格式表示
# 時間和日期格式均為iso8601# 日期表示data_today:2018-04-22# 時間格式# 下面代表北京時間2018,04,22的16:55:30,因為北京位於東八區,所以後面加了08:00,時間的秒可以寫到小數點後兩位time_now:2018-04-22T16:55:30+08:00
三、yaml檔案讀取

匯入yaml模組,需使用官方的匯入方法,可以相容windows和linux平台

import yamltry:    from yaml import CLoader as Loader, CDumper as Dumperexcept ImportError:    from yaml import Loader, Dumperyaml_file= open("path", "r")data = yaml.load(yaml_file)
四、 使用案例4.1 待操作yaml檔案
# 檔案名稱test.yamlbind1:  hostname: ubuntu test  remote_users:    - user1:      username: root      auth_type: ssh-key      password: 123    - user2:      username: gungun      auth_type: ssh-password      password: gungun123  groups:    - bj_group  user_profiles:    - gungun    - xiangqiangun
4.2 yaml檔案讀取樣本
import yamltry:    from yaml import CLoader as Loader, CDumper as Dumperexcept ImportError:    from yaml import Loader, Dumperyaml_file = open("test.yaml",‘r‘)data = yaml.load(yaml_file)print("data_type:", type(data))print("data_content:\n", data)

列印結果:

data_content: {‘bind1‘: {‘user_profiles‘: [‘gungun‘, ‘xiangqiangun‘], ‘hostname‘: ‘ubuntu test‘, ‘groups‘: [‘bj_group‘], ‘remote_users‘: [{‘username‘: ‘root‘, ‘auth_type‘: ‘ssh-key‘, ‘user1‘: None, ‘password‘: 123}, {‘username‘: ‘gungun‘, ‘auth_type‘: ‘ssh-password‘, ‘user2‘: None, ‘password‘: ‘gungun123‘}]}}

01 python基礎——python解析yaml類型檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.