上一篇筆記記錄了Python中的pyyaml庫對yaml文件進行讀寫,但了解到ruamel.yaml也能對yaml文件進行讀寫,於是想嘗試一下它的用法。
一,注意
這里首先要更正一下網上大部分博客的說法:使用PyYAML寫入時不是yaml的標准形式。例如使用PyYAML將字典嵌套字典的數據寫入yaml文件時,寫入的yaml文件里會出現帶{}的數據。實際我在寫代碼的過程中發現PyYAML5.3.1版本並不會出現這種情況。如下所示:
使用PyYAML庫寫入yaml文件
# @author: 給你一頁白紙
import yaml
data = {
"str": "Hello world.",
"int": 110,
"list": [10, "she", ["he", "it"]],
"dict": {"account":"xiaoqq", "password": {"pwd1": 123456, "pwd2": "water"}},
"tuple": (100, "a")
}
with open('./writeYamlData.yml', 'w', encoding='utf-8') as f:
yaml.dump(data=data, stream=f, allow_unicode=True)
寫入后的yaml文件內容如下:
dict:
account: xiaoqq
password:
pwd1: 123456
pwd2: water
int: 110
list:
- 10
- she
- - he
- it
str: Hello world.
tuple: !!python/tuple
- 100
- a
二,安裝ruamel.yaml庫
安裝命令:
pip install ruamel.yaml
# 安裝速度慢則加上鏡像源
pip install ruamel.yaml -i https://pypi.tuna.tsinghua.edu.cn/simple
使用時導入:
from ruamel import yaml
三,ruamel.yaml寫入yaml文件
使用yaml.dump()方法寫入,代碼展示如下:
# @author: 給你一頁白紙
from ruamel import yaml
data = {
"str": "Hello world.",
"int": 110,
"list": [10, "she", ["he", "it"]],
"dict": {"account":"xiaoqq", "password": {"pwd1": 123456, "pwd2": "water"}},
"tuple": (100, "a")
}
# path為yaml文件的絕對路徑
path ='./writeYamlData.yml'
with open(path, 'w', encoding='utf-8') as f:
yaml.dump(data, f, Dumper=yaml.RoundTripDumper)
寫入結果如下:
str: Hello world.
int: 110
list:
- 10
- she
- - he
- it
dict:
account: xiaoqq
password:
pwd1: 123456
pwd2: water
tuple:
- 100
- a
注意:這里yaml.dump()里加上l了參數Dumper=yaml.RoundTripDumper。不加該參數則寫入結果如下:
dict:
account: xiaoqq
password: {pwd1: 123456, pwd2: water}
int: 110
list:
- 10
- she
- [he, it]
str: Hello world.
tuple: !!python/tuple [100, a]
四,ruamel.yaml讀取yaml文件
yaml文件數據如下:
dict:
account: xiaoqq
password:
pwd1: 123456
pwd2: water
int: 110
list:
- 10
- she
- - he
- it
str: Hello world.
tuple: !!python/tuple
- 100
- a
使用yaml.load()方法讀取,代碼展示如下:
# @author: 給你一頁白紙
from ruamel import yaml
# path為yaml文件的絕對路徑
path ='./writeYamlData.y'
with open(path, 'r', encoding='utf-8') as doc:
content = yaml.load(doc, Loader=yaml.Loader)
print(content)
讀取結果如下:
C:\Users\xiaoqq\AppData\Local\Programs\Python\Python37\python.exe C:/Users/xiaoqq/Desktop/test_project/readYaml.py
{'dict': {'account': 'xiaoqq', 'password': {'pwd1': 123456, 'pwd2': 'water'}}, 'int': 110, 'list': [10, 'she', ['he', 'it']], 'str': 'Hello world.', 'tuple': (100, 'a')}
Process finished with exit code 0
ruamel.yaml庫繼承子PyMYAL庫,讀寫方法基本相同,目前來說可以根據自己的習慣選擇使用 ruamel.yaml 還是 PyMYAL 進行yaml文件的讀寫操作。