詳解Python yaml模塊
一、yaml文件介紹
yaml是一個(gè)專門用來寫配置文件的語言。
1. yaml文件規(guī)則
區(qū)分大小寫; 使用縮進(jìn)表示層級(jí)關(guān)系; 使用空格鍵縮進(jìn),而非Tab鍵縮進(jìn) 縮進(jìn)的空格數(shù)目不固定,只需要相同層級(jí)的元素左側(cè)對(duì)齊; 文件中的字符串不需要使用引號(hào)標(biāo)注,但若字符串包含有特殊字符則需用引號(hào)標(biāo)注; 注釋標(biāo)識(shí)為#2. yaml文件數(shù)據(jù)結(jié)構(gòu)
對(duì)象:鍵值對(duì)的集合(簡稱 '映射或字典')鍵值對(duì)用冒號(hào) “:” 結(jié)構(gòu)表示,冒號(hào)與值之間需用空格分隔
數(shù)組:一組按序排列的值(簡稱 '序列或列表')數(shù)組前加有 “-” 符號(hào),符號(hào)與值之間需用空格分隔
純量(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 yamlimport osdef 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 datacurrent_path = os.path.abspath('.')yaml_path = os.path.join(current_path, 'config.yaml')get_yaml_data(yaml_path)'''***獲取yaml文件數(shù)據(jù)***# yaml鍵值對(duì):即python中字典usr: mypsw: 123455類型:<class ’str’>***轉(zhuǎn)化yaml數(shù)據(jù)為字典或列表***{’usr’: ’my’, ’psw’: 123455}類型:<class ’dict’>'''
3. yaml文件數(shù)據(jù)為鍵值對(duì)
(1)yaml文件中內(nèi)容為鍵值對(duì):
# yaml鍵值對(duì):即python中字典usr: mypsw: 123455s: ' abcn'
python解析yaml文件后獲取的數(shù)據(jù):
{’usr’: ’my’, ’psw’: 123455, ’s’: ’ abcn’}
(2)yaml文件中內(nèi)容為“鍵值對(duì)’嵌套'鍵值對(duì)'
# yaml鍵值對(duì)嵌套:即python中字典嵌套字典usr1: name: a psw: 123usr2: name: b psw: 456
python解析yaml文件后獲取的數(shù)據(jù):
{’usr1’: {’name’: ’a’, ’psw’: 123}, ’usr2’: {’name’: ’b’, ’psw’: 456}}
(3)yaml文件中“鍵值對(duì)”中嵌套“數(shù)組”
python解析yaml文件后獲取的數(shù)據(jù):
# yaml鍵值對(duì)中嵌套數(shù)組usr3: - a - b - cusr4: - 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ù)組”中嵌套“鍵值對(duì)”
# yaml'數(shù)組'中嵌套'鍵值對(duì)'- 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: 'namen' # 特殊字符串:{’spec_s_val’: ’namen’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 fishtest: *animal3
python讀取的數(shù)據(jù)
{’animal3’: ’fish’, ’test’: ’fish’}
三、python中讀取多個(gè)yaml文檔
1. 多個(gè)文檔在一個(gè)yaml文件,使用 --- 分隔方式來分段
如:yaml文件中數(shù)據(jù)
# 分段yaml文件中多個(gè)文檔---animal1: dogage: 2---animal2: catage: 3
2. python腳本讀取一個(gè)yaml文件中多個(gè)文檔方法
python獲取yaml數(shù)據(jù)時(shí)需使用load_all函數(shù)來解析全部的文檔,再從中讀取對(duì)象中的數(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對(duì)象生成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對(duì)象生成yaml文檔import yamldef 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: zhangstudents: [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: zhangstudents:- 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模塊的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 詳解盒子端CSS動(dòng)畫性能提升2. CSS hack用法案例詳解3. PHP字符串前后字符或空格刪除方法介紹4. 使用HttpClient增刪改查ASP.NET Web API服務(wù)5. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除6. ASP.NET Core實(shí)現(xiàn)中間件的幾種方式7. input submit、button和回車鍵提交數(shù)據(jù)詳解8. 使用HttpClient消費(fèi)ASP.NET Web API服務(wù)案例9. ASP常用日期格式化函數(shù) FormatDate()10. 詳解瀏覽器的緩存機(jī)制
