詳解Python yaml模塊
一、yaml文件介紹
yaml是一個(gè)專門用來寫配置文件的語言。
1. yaml文件規(guī)則
- 區(qū)分大小寫;
- 使用縮進(jìn)表示層級關(guān)系;
- 使用空格鍵縮進(jìn),而非Tab鍵縮進(jìn)
- 縮進(jìn)的空格數(shù)目不固定,只需要相同層級的元素左側(cè)對齊;
- 文件中的字符串不需要使用引號標(biāo)注,但若字符串包含有特殊字符則需用引號標(biāo)注;
- 注釋標(biāo)識(shí)為#
2. yaml文件數(shù)據(jù)結(jié)構(gòu)
- 對象:鍵值對的集合(簡稱 "映射或字典")
鍵值對用冒號 “:” 結(jié)構(gòu)表示,冒號與值之間需用空格分隔
- 數(shù)組:一組按序排列的值(簡稱 "序列或列表")
數(shù)組前加有 “-” 符號,符號與值之間需用空格分隔
- 純量(scalars):單個(gè)的、不可再分的值(如:字符串、bool值、整數(shù)、浮點(diǎn)數(shù)、時(shí)間、日期、null等)
None值可用null可 ~ 表示
二、python中讀取yaml配置文件
1. 前提條件
python中讀取yaml文件前需要安裝pyyaml和導(dǎo)入yaml模塊:
- 使用yaml需要安裝的模塊為pyyaml(pip3 install pyyaml);
- 導(dǎo)入的模塊為yaml(import yaml)
2. 讀取yaml文件數(shù)據(jù)
python通過open方式讀取文件數(shù)據(jù),再通過load函數(shù)將數(shù)據(jù)轉(zhuǎn)化為列表或字典;
import yaml import os def get_yaml_data(yaml_file): # 打開yaml文件 print("***獲取yaml文件數(shù)據(jù)***") file = open(yaml_file, 'r', encoding="utf-8") file_data = file.read() file.close() print(file_data) print("類型:", type(file_data)) # 將字符串轉(zhuǎn)化為字典或列表 print("***轉(zhuǎn)化yaml數(shù)據(jù)為字典或列表***") data = yaml.load(file_data) print(data) print("類型:", type(data)) return data current_path = os.path.abspath(".") yaml_path = os.path.join(current_path, "config.yaml") get_yaml_data(yaml_path) """ ***獲取yaml文件數(shù)據(jù)*** # yaml鍵值對:即python中字典 usr: my psw: 123455 類型:<class 'str'> ***轉(zhuǎn)化yaml數(shù)據(jù)為字典或列表*** {'usr': 'my', 'psw': 123455} 類型:<class 'dict'> """
3. yaml文件數(shù)據(jù)為鍵值對
(1)yaml文件中內(nèi)容為鍵值對:
# yaml鍵值對:即python中字典 usr: my psw: 123455 s: " abc\n"
python解析yaml文件后獲取的數(shù)據(jù):
{'usr': 'my', 'psw': 123455, 's': ' abc\n'}
(2)yaml文件中內(nèi)容為“鍵值對'嵌套"鍵值對"
# yaml鍵值對嵌套:即python中字典嵌套字典 usr1: name: a psw: 123 usr2: name: b psw: 456
python解析yaml文件后獲取的數(shù)據(jù):
{'usr1': {'name': 'a', 'psw': 123}, 'usr2': {'name': 'b', 'psw': 456}}
(3)yaml文件中“鍵值對”中嵌套“數(shù)組”
python解析yaml文件后獲取的數(shù)據(jù):
# yaml鍵值對中嵌套數(shù)組 usr3: - a - b - c usr4: - b
python解析yaml文件后獲取的數(shù)據(jù):
{'usr3': ['a', 'b', 'c'], 'usr4': ['b']}
4. yaml文件數(shù)據(jù)為數(shù)組
(1)yaml文件中內(nèi)容為數(shù)組
# yaml數(shù)組 - a - b - 5
python解析yaml文件后獲取的數(shù)據(jù):
['a', 'b', 5]
(2)yaml文件“數(shù)組”中嵌套“鍵值對”
# yaml"數(shù)組"中嵌套"鍵值對" - usr1: aaa - psw1: 111 usr2: bbb psw2: 222
python解析yaml文件后獲取的數(shù)據(jù):
[{'usr1': 'aaa'}, {'psw1': 111, 'usr2': 'bbb', 'psw2': 222}]
5. yaml文件中基本數(shù)據(jù)類型:
# 純量 s_val: name # 字符串:{'s_val': 'name'} spec_s_val: "name\n" # 特殊字符串:{'spec_s_val': 'name\n' num_val: 31.14 # 數(shù)字:{'num_val': 31.14} bol_val: true # 布爾值:{'bol_val': True} nul_val: null # null值:{'nul_val': None} nul_val1: ~ # null值:{'nul_val1': None} time_val: 2018-03-01t11:33:22.55-06:00 # 時(shí)間值:{'time_val': datetime.datetime(2018, 3, 1, 17, 33, 22, 550000)} date_val: 2019-01-10 # 日期值:{'date_val': datetime.date(2019, 1, 10)}
6. yaml文件中引用
yaml文件中內(nèi)容
animal3: &animal3 fish test: *animal3
python讀取的數(shù)據(jù)
{'animal3': 'fish', 'test': 'fish'}
三、python中讀取多個(gè)yaml文檔
1. 多個(gè)文檔在一個(gè)yaml文件,使用 --- 分隔方式來分段
如:yaml文件中數(shù)據(jù)
# 分段yaml文件中多個(gè)文檔 --- animal1: dog age: 2 --- animal2: cat age: 3
2. python腳本讀取一個(gè)yaml文件中多個(gè)文檔方法
python獲取yaml數(shù)據(jù)時(shí)需使用load_all函數(shù)來解析全部的文檔,再從中讀取對象中的數(shù)據(jù)
# yaml文件中含有多個(gè)文檔時(shí),分別獲取文檔中數(shù)據(jù) def get_yaml_load_all(yaml_file): # 打開yaml文件 file = open(yaml_file, 'r', encoding="utf-8") file_data = file.read() file.close() all_data = yaml.load_all(file_data) for data in all_data: print(data) current_path = os.path.abspath(".") yaml_path = os.path.join(current_path, "config.yaml") get_yaml_load_all(yaml_path) """結(jié)果 {'animal1': 'dog', 'age': 2} {'animal2': 'cat', 'age': 3} """
四、python對象生成yaml文檔
1. 直接導(dǎo)入yaml(即import yaml)生成的yaml文檔
通過yaml.dump()方法不會(huì)將列表或字典數(shù)據(jù)進(jìn)行轉(zhuǎn)化yaml標(biāo)準(zhǔn)模式,只會(huì)將數(shù)據(jù)生成到y(tǒng)aml文檔中
# 將python對象生成yaml文檔 import yaml def generate_yaml_doc(yaml_file): py_object = {'school': 'zhang', 'students': ['a', 'b']} file = open(yaml_file, 'w', encoding='utf-8') yaml.dump(py_object, file) file.close() current_path = os.path.abspath(".") yaml_path = os.path.join(current_path, "generate.yaml") generate_yaml_doc(yaml_path) """結(jié)果 school: zhang students: [a, b] """
2. 使用ruamel模塊中的yaml方法生成標(biāo)準(zhǔn)的yaml文檔
(1)使用ruamel模塊中yaml前提條件
- 使用yaml需要安裝的模塊:ruamel.yaml(pip3 install ruamel.yaml);
- 導(dǎo)入的模塊:from ruamel import yaml
(2)ruamel模塊生成yaml文檔
def generate_yaml_doc_ruamel(yaml_file): from ruamel import yaml py_object = {'school': 'zhang', 'students': ['a', 'b']} file = open(yaml_file, 'w', encoding='utf-8') yaml.dump(py_object, file, Dumper=yaml.RoundTripDumper) file.close() current_path = os.path.abspath(".") yaml_path = os.path.join(current_path, "generate.yaml") generate_yaml_doc_ruamel(yaml_path) """結(jié)果 school: zhang students: - a - b """
(3)ruamel模塊讀取yaml文檔
# 通過from ruamel import yaml讀取yaml文件 def get_yaml_data_ruamel(yaml_file): from ruamel import yaml file = open(yaml_file, 'r', encoding='utf-8') data = yaml.load(file.read(), Loader=yaml.Loader) file.close() print(data) current_path = os.path.abspath(".") yaml_path = os.path.join(current_path, "dict_config.yaml") get_yaml_data_ruamel(yaml_path)
以上就是詳解Python yaml模塊的詳細(xì)內(nèi)容,更多關(guān)于Python yaml模塊的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
實(shí)現(xiàn)Python圖形界面框架TkInter寫GUI界面應(yīng)用簡介過程操作
TkInter是Python用于開發(fā)GUI界面的標(biāo)準(zhǔn)庫,如果你想快速開發(fā)一個(gè)帶有GUI界面的小工具(笑小程序),且又能同時(shí)在Linux、Windows、Mac上使用,TkInter天生支持跨平臺(tái),天生具備穩(wěn)定性,我認(rèn)為它能滿足內(nèi)部工具的簡單需求2021-09-09人臉檢測實(shí)戰(zhàn)終極之OpenCV+Python實(shí)現(xiàn)人臉對齊
這篇文章主要是為了演示如何使用 OpenCV、Python 和面部標(biāo)志從而實(shí)現(xiàn)對齊人臉。文中示例代碼對我們的工作或?qū)W習(xí)有一定的幫助,感興趣的小伙伴可以學(xué)習(xí)一下2021-12-12Python數(shù)據(jù)類型之String字符串實(shí)例詳解
這篇文章主要介紹了Python數(shù)據(jù)類型之String字符串,結(jié)合實(shí)例形式詳細(xì)講解了Python字符串的概念、定義、連接、格式化、轉(zhuǎn)換、查找、截取、判斷等常見操作技巧,需要的朋友可以參考下2019-05-05Python編寫可視化界面的詳細(xì)教程(Python+PyCharm+PyQt)
最近開始學(xué)習(xí)Python,但只限于看理論,編幾行代碼,覺得沒有意思,就想能不能用Python編寫可視化的界面,遂查找了相關(guān)資料,發(fā)現(xiàn)了PyQt,所以本文介紹了Python+PyCharm+PyQt編寫可視化界面的詳細(xì)教程,需要的朋友可以參考下2024-07-07