python解析.yml/.yaml文件--pyyaml模塊(第三方)


第一part:YAML文件介紹


 1.YAML文件的定義:是一種比XML和JSON更輕的文件格式,也更簡單更強大,它可以通過縮進來表示結構,是不是與Python使用有異曲同工之處;

2.YAML文件的特點:

1)YAML的可讀性好。

2)YAML和腳本語言的交互性好。

3)YAML使用實現語言的數據類型。

其官網描述:YAML語言的設計目標,就是方便人類讀寫。

3.YAML文件規則:

1)區分大小寫;

2)使用縮進表示層級關系;

3)使用空格鍵縮進,而非Tab鍵縮進

4)縮進的空格數目不固定,只需要相同層級的元素左側對齊;

5)文件中的字符串不需要使用引號標注,但若字符串包含有特殊字符則需用引號標注;

6)注釋標識為#

4.YAML文件數據結構

 

1)對象:鍵值對的集合(簡稱 "映射或字典")
2)鍵值對用冒號 “:” 結構表示,冒號與值之間需用空格分隔

3)數組:一組按序排列的值(簡稱 "序列或列表")
數組前加有 “-” 符號,符號與值之間需用空格分隔

4)純量(scalars):單個的、不可再分的值(如:字符串、bool值、整數、浮點數、時間、日期、null等)
None值:可用null、可 ~ 表示

 


 第二part:yaml對象與python對象對應表


 官網:https://pyyaml.org/wiki/PyYAMLDocumentation

YAML tags and Python types

The following table describes how nodes with different tags are converted to Python objects.

YAML tag Python type
Standard YAML tags  
!!null None
!!bool bool
!!int int or long (int in Python 3)
!!float float
!!binary str (bytes in Python 3)
!!timestamp datetime.datetime
!!omap!!pairs list of pairs
!!set set
!!str str or unicode (str in Python 3)
!!seq list
!!map dict
Python-specific tags  
!!python/none None
!!python/bool bool
!!python/bytes (bytes in Python 3)
!!python/str str (str in Python 3)
!!python/unicode unicode (str in Python 3)
!!python/int int
!!python/long long (int in Python 3)
!!python/float float
!!python/complex complex
!!python/list list
!!python/tuple tuple
!!python/dict dict
Complex Python tags  
!!python/name:module.name module.name
!!python/module:package.module package.module
!!python/object:module.cls module.cls instance
!!python/object/new:module.cls module.cls instance
!!python/object/apply:module.f value of f(...)


 第三part:Python讀取yaml文件的數據


 python對yaml文件的操作,需要安裝第三方模塊pyyaml,安裝方式有兩種:

第一種:命令行安裝--》pip install pyyaml  

第二種:pychram安裝---》pycharm--project---project interpreter中搜索pyyaml進行安裝

 python讀取yaml文件的規則:python通過open方式讀取文件數據,再通過yaml.load()函數將數據轉化為列表或字典;

整體代碼為:

import yaml
with open("data3.yaml",'r', encoding="utf-8") as fp:
result=fp.read()
print(type(result))
get_result= yaml.load(result,Loader=yaml.SafeLoader)
print(get_result,type(get_result))

執行結果,如下:



第四part:yaml文件對應python類型的詳細寫法:

 1.yaml鍵值對:即python中字典:

#yaml文件的寫法:

username: huangshan
password: 123456

#python解析yaml文件后獲取的數據:

{'usrname': 'wood', 'password': 123456}
yaml文件中內容為“鍵值對'嵌套"鍵值對"


2 .yaml鍵值對嵌套:即python中字典嵌套字典:

#yaml文件的寫法:

usr1:
name: a
psw: 123
usr2:
name: b
psw: 456

#python解析yaml文件后獲取的數據:


{'usr1': {'name': 'a', 'psw': 123}, 'usr2': {'name': 'b', 'psw': 456}}


3.yaml文件中“鍵值對”中嵌套“列表:

# yaml鍵值對中嵌套數組


usr3:
- a
- b
- c
usr4:
- d

#python解析yaml文件后獲取的數據:

 

{'usr3': ['a', 'b', 'c'], 'usr4': ['d']}

 

4. yaml鍵值對中嵌套數組:

# yaml鍵值對中嵌套數組

usr3:
- a
- b
- c
usr4:
- d

 

#python解析yaml文件后獲取的數據:


{'usr3': ['a', 'b', 'c'], 'usr4': ['d']}

5.yaml文件數據為數組:

(1)yaml文件中內容為數組

# yaml數組:


- a
- b
- 5


#python解析yaml文件后獲取的數據:


['a', 'b', 5]


(2)yaml文件“數組”中嵌套“鍵值對”

# yaml"數組"中嵌套"鍵值對":


- usr1: aaa
- psw1: 111
usr2: bbb
psw2: 222


python解析yaml文件后獲取的數據:

[{'usr1': 'aaa'}, {'psw1': 111, 'usr2': 'bbb', 'psw2': 222}]


6.yaml文件中基本數據類型:

# 純量定義


s_val: wood # 字符串:{'s_val': 'wood'}
spec_s_val: "name\n" # 特殊字符串:{'spec_s_val': 'name\n'
num_val: 30.14 # 數字:{'num_val': 30.14}
bol_val: true # 布爾值:{'bol_val': True}
nul_val: null # null值:{'nul_val': None}
nul_val1: ~ # null值:{'nul_val1': None}
date_val: 2020-06-01 # 日期值:{'date_val': datetime.date(2020, 06, 01)}

7.yaml文件中引用:

#yaml文件中內容

animal: &animal tiger

test: *animal

#python讀取的數據

{'animal': 'tiger', 'test': 'tiger'}

 


 第五part:python讀取一個yaml文件中多個文檔


 1. 多個文檔在一個yaml文件,使用 --- 分隔方式來分段

# 分段yaml文件中多個文檔
---
student1: zhangsan
age: 18
---
student2: lisi
age: 20

 

2. python腳本讀取一個yaml文件中多個文檔方法
python獲取yaml數據時需使用load_all函數來解析全部的文檔,再從中讀取對象中的數據
# yaml文件中含有多個文檔時,分別獲取文檔中數據,整體代碼:

import yaml
with open('data3.yaml', 'r', encoding="utf-8") as file:
file_data = file.read()
all_data = yaml.load_all(file_data, Loader=yaml.SafeLoader)
for data in all_data:
print(data)


執行結果為:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM