Python使用yaml模塊操作YAML文檔的方法

1. YAML簡介

YAML是可讀性高,用來表達數據序列化格式的,專用於寫配置文件的語言。YAML文件其實也是一種配置文件類型,後綴名是.yaml或.yml都可以。其以數據為中心,使用空白,縮進,分行組織數據,從而使得表示更加簡潔。

2. 語法規則

  • 大小寫敏感
  • 使用縮進表示層級關系
  • 使用空格鍵縮進,而非Tab鍵縮進
  • 縮進的空格數目不重要,隻需要相同層級的元素左側對齊
  • 文件中的字符串不需要使用引號標註,但若字符串包含有特殊字符則需用引號標註
  • 註釋標識為 #

3. 文件數據結構

對象:鍵值對的集合(簡稱"映射或字典")

鍵值對用冒號 “:” 結構表示 冒號與值之間需用空格分隔

數組:一組按序排列的值(簡稱"序列或列表")

數組前加有 “-” 符號 符號與值之間需用空格分隔

純量(scalars):單個的、不可再份的值(如:字符串、bool值、整數、浮點數、時間、日期、null等)

None值可用null,也可用~表示

4. YAML數據格式示例

# 對象:yaml鍵值對;即Python中字典
user: 'admin'
pwd: 'admin@123'
site: "www.yaml.com"
# 解析後: {'user': 'admin', 'password': 'admin@123', 'site': 'www.yaml.com'}

# 2. 數組:yaml鍵值對中嵌套數組
user2:
 - a
 - b
 - c
user3:
 - d
# 解析後:{'user2':['a','b','c'],'user3':['d']}

# 3. 純量
val_name: name      # 字符串: {'val_name': 'name'}
spec_val: "name\n" # 特殊字符串: {'spec_val': 'name\n'}
pi_val: 3.14        # 數字: {'pi_val': 3.14}
bol_val: true       # 佈爾值: {'bol_val': true}
nul_val: null       # null值: {'nul_val': None}
nul_val: ~          # null值: {'nul_val': None}
time_val: 2023-02-03t22:33:22.33-03:00      # 時間值:{'time_val': datetime.datetime(2023, 2, 3, 22, 33, 22, 330000)}
date_val: 2024-01-01        # 日期值:{'date_val': datetime.date(2024, 1, 1)}

# 4. 引用
name: &name 白雲
tester: *name
# 相當於
name: 白雲
tester: 白雲
# 解析後內容:{'name': '白雲', 'tester': '白雲'}

# 5. 強制轉換
str: !!str 3.14
int: !!int "666"
# 輸出: {'str': '3.14','int': 123}

5. 安裝yaml庫

pip install pyyaml

6. 讀取YAML

6.1 讀取鍵值對或嵌套鍵值對

yaml文件內容為:

user1:
 name: xm
 stu: 101
user2:
 name: xh
 stu: 102
user3:
 name: xl
 stu: 103

程序代碼:

import yaml
import os
class ReadYAML(object):
    def read_yaml(self,yaml_file):
        with open(yaml_file,'r',encoding='utf-8') as f:
            file_data = f.read()
            print("file_data類型:",type(file_data))
            data = yaml.safe_load(file_data)
            print("data類型:",type(data))
        
        return data



if __name__ == "__main__":
    base_name = os.path.dirname(os.path.realpath(__file__))
    yaml_path = os.path.join(base_name,'test.yaml')
    ry = ReadYAML()
    res = ry.read_yaml(yaml_path)
    print(res)

輸出結果:

file_data類型: <class 'str'>
data類型: <class 'dict'>
{'user1': {'name': 'xm', 'stu': 101}, 'user2': {'name': 'xh', 'stu': 102}, 'user3': {'name': 'xl', 'stu': 103}}

6.2 讀取數組類型

yaml文件內容為:

class1:
 - stu1
 - stu2
 - stu3
class2:
 - stu2

程序代碼:

import yaml
import os
class ReadArraysYAML(object):
    def read_yaml(self,yaml_file):
        with open(yaml_file,'r',encoding='utf-8') as f:
            file_data = f.read()
            # print("file_data類型:",type(file_data))
            data = yaml.safe_load(file_data)
            # print("data類型:",type(data))
        
        return data


if __name__ == "__main__":
    base_name = os.path.dirname(os.path.realpath(__file__))
    yaml_path = os.path.join(base_name,'arrays.yaml')
    ry = ReadArraysYAML()
    res = ry.read_yaml(yaml_path)
    print(res)

輸出結果:

{'class1': ['stu1', 'stu2', 'stu3'], 'class2': ['stu2']}

6.3 多文檔同在一份yaml文件中時的讀取方法

yaml文件內容:

# 分段yaml文件中存在多個文檔
---
animal1: dog
age: 1
---
animal2: cat
age: 2

程序代碼:

"""
多文檔同在一份yaml文件中時的讀取方法(使用yaml.safe_load_all())
"""
import yaml
import os
def get_yaml_load_all(yaml_file):
    file = open(yaml_file,'r',encoding='utf-8')
    file_data = file.read()
    file.close()
    all_data = yaml.safe_load_all(file_data)
    for data in all_data:
        print(data)
if __name__ == "__main__":
    current_path = os.path.dirname(__file__)
    print(current_path)
    yaml_path = os.path.join(current_path,'muti.yaml')
    get_yaml_load_all(yaml_path)

輸出結果:

d:\PyProject\YAML
{'animal1': 'dog', 'age': 1}
{'animal2': 'cat', 'age': 2}

6.4 向YAML文檔寫入

程序代碼:

"""
使用yaml.dump()方法將列表或字典數據寫入進已存在的yaml文檔
"""
import yaml
import os
def generate_yaml_doc(yaml_file):
    py_object = {'school':'Fxxking U','student':['stu1','stu2']}
    file = open(yaml_file,'w',encoding='utf-8')
    yaml.safe_dump(py_object,file)
    file.close()
if __name__ == "__main__":
    current_path = os.path.dirname(__file__)
    print(current_path)
    yaml_path = os.path.join(current_path,'generateYAML.yaml')
    generate_yaml_doc(yaml_path)

寫入後,YAML文檔內容:

school: Fxxking U
student:
- stu1
- stu2

註:若想要以追加的形式寫入,隻需將open()中的’w’改為’a’即可

6.5 更新/修改 YAML文件內容

修改前YAML文件內容:

school: Fxxking U
student:
- stu1
- stu2

程序代碼:

import yaml
import os
from readArraysYAML import ReadArraysYAML

def update_yaml(k,v,yaml_file):
    readY = ReadArraysYAML()
    old_data = readY.read_yaml(yaml_file)
    old_data[k] = v     # 修改讀取的數據,如果k不存在則新增一組鍵值對
    with open(yaml_file,'w',encoding='utf-8') as f:
        yaml.safe_dump(old_data,f)

if __name__ == "__main__":
    current_path = os.path.dirname(__file__)
    yaml_path = os.path.join(current_path,'generateYAML.yaml')
    k = 'school'
    v = 'SZ U'
    update_yaml(k,v,yaml_path)

修改後,YAML文件內容:

school: SZ U
student:
- stu1
- stu2

7. 使用ruamel模塊將數據轉換為標準的yaml內容

安裝ruamel庫

pip install ruamel.yaml

程序代碼:

from ruamel import yaml
import os
def generate_yaml_doc_ruamel(yaml_file):
    py_object = {'file_type':'ruamel_yaml','school':'Fxxking U','student':['c','d']}
    with open(yaml_file,'w',encoding='utf-8') as f:
        yaml.dump(py_object,f,Dumper=yaml.RoundTripDumper)
if __name__ == "__main__":
    current_path = os.path.dirname(__file__)
    yaml_path = os.path.join(current_path,'ruamelGenerateYAML.yaml')
    generate_yaml_doc_ruamel(yaml_path)
    print("寫入成功!")

寫入後,YAML文件內容:

file_type: ruamel_yaml
school: Fxxking U
student:
- c
- d

到此這篇關於Python使用yaml模塊操作YAML文檔的文章就介紹到這瞭,更多相關Python使用yaml模塊內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: