python處理yaml文件的操作方法
yaml文件簡介
yaml 文件是一種數(shù)據(jù)序列化語言,廣泛用于配置文件、日志文件、等
語言特點
- 大小寫敏感
- 使用縮進表示層級關(guān)系
- 縮進時不允許使用Tab鍵,只允許使用空格。
- 縮進的空格數(shù)目不重要,只要相同層級的元素左側(cè)對齊即可
yaml數(shù)據(jù)結(jié)構(gòu)
yaml語言包含三種數(shù)據(jù)結(jié)構(gòu):
- mappings (hashes/dictionaries) 對象
- sequences (arrays/lists) 數(shù)組
- scalars (strings/numbers) 純量
以下是標記語言和轉(zhuǎn)化為python 對象后的輸出
數(shù)組
數(shù)組以 - 和 空格 來標記
- name1 - name2 - name3
output: 轉(zhuǎn)為list
['name1', 'name2', 'name3']
對象
對象用: 和 空格 標識
name: Ling email: ww.aa.com
output: 轉(zhuǎn)為dict
{'name': 'Ling', 'email': 'ww.aa.com'}
數(shù)據(jù)對象混合
對象value為數(shù)組/ 對象
american: - Boston Red Sox - Detroit Tigers - New York Yankees national: - New York Mets - Chicago Cubs - Atlanta Braves: - A - B
多維數(shù)組
- - Boston Red Sox - Detroit Tigers - New York Yankees - - New York Mets - Chicago Cubs - Atlanta Braves
純量
- 字符串
- 布爾值
- 整數(shù)
- 浮點數(shù)
- Null
- 時間
- 日期
boolean: - TRUE #true,True,TRUE都可以 - FALSE #false,F(xiàn)alse, FALSE都可以 float: - 3.14 - 6.8523015e+5 #可以使用科學(xué)計數(shù)法 int: - 123 - 0b1010_0111_0100_1010_1110 #二進制表示 kongzhi: parent: ~ #使用~表示null class: null #null也表示null string: - 哈哈 - 'Hello world: from this way' #如果字符串之中包含空格或特殊字符,需要放在引號之中,可以使用雙引號或者單引號包裹特殊字符 - 寫多行 #換行服會轉(zhuǎn)義成空格 date: - 2018-02-17 #日期必須使用ISO 8601格式,即yyyy-MM-dd - 2018-02-17 12:23:34 #標準帶時間格式
output如下:
{'boolean': [True, False], 'float': [3.14, 685230.15], 'int': [123, 685230], 'kongzhi': {'parent': None, 'class': None}, 'string': ['哈哈', 'Hello world: from this way', '寫多行'], 'date1': [datetime.date(2018, 2, 17), datetime.datetime(2018, 2, 17, 12, 23, 34)]}
注意上述date轉(zhuǎn)換成python 字典后,轉(zhuǎn)成json會報錯
xx={'date1': [datetime.date(2018, 2, 17), datetime.datetime(2018, 2, 17, 12, 23, 34)]} print(json.dumps(xx, indent=4)) # 運行錯誤如下: TypeError: Object of type date is not JSON serializable
注釋
注釋以“#” 標識
- name1 #this is first name - name2 - name3
錨點和引用
& 用來建立錨點,<< 表示合并到當前數(shù)據(jù),* 用來引用錨點
舉例如下:
defaults: &defaults adapter: postgres host: localhost development: database: myapp_development <<: *defaults test: database: myapp_test <<: *defaults
python操作yaml文件
安裝工具包
pip install pyyaml
pyyaml官網(wǎng)文檔
https://pyyaml.org/wiki/PyYAMLDocumentation
常用方法
這里的常用方法和 json 操作類似
將yml文件轉(zhuǎn)換成 python中數(shù)據(jù)
由于 yaml.load()
方法不安全,建議使用yaml.safe_load()
函數(shù)
import yaml # 直接打開文件,獲取文件內(nèi)容,轉(zhuǎn)換成python dict 數(shù)據(jù)格式 # 這里要考慮關(guān)閉文件 file_data = open('./config/login_data.yaml') data = yaml.load(file_data, yaml.SafeLoader) # 相當于 safe_load 方法 print(data) file1.close() # 使用with 方法,可以不用手動關(guān)閉文件 # 這里設(shè)置encoding 是為了yaml 文件有中文時進行處理 with open('./config/login_data.yaml', encoding='utf-8') as f: elem_locators = yaml.safe_load(f) # 傳入的是 yaml字符串或者文件句柄 print(elem_locators)
將python數(shù)據(jù)轉(zhuǎn)換成 寫入yml 文件
使用 yaml.dump 函數(shù),暫時不在此介紹
清空yaml文件
trucate()
yaml 常用的方法就是 讀取、寫入 和 清空
讀取文件的內(nèi)容
可以加多個fixtrue
可以加多個斷言
注意點
yaml中有中文
如yaml中有中文,需要使用 字符串.encode('utf-8')或打開文件時指定encoding='utf-8'
參考鏈接
yaml語言介紹
- YAML 入門教程: https://www.runoob.com/w3cnote/yaml-intro.html
- YAML Ain’t Markup Language (YAML™) version 1.2: https://yaml.org/spec/1.2.2/#chapter-2-language-overview
- YAML 語言教程: https://www.ruanyifeng.com/blog/2016/07/yaml.html
python 操作yaml
- PyYAML Documentation https://pyyaml.org/wiki/PyYAMLDocumentation
到此這篇關(guān)于python處理yaml文件的操作方法的文章就介紹到這了,更多相關(guān)python處理yaml文件 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
numpy如何按條件給元素賦值np.where、np.clip
這篇文章主要介紹了numpy如何按條件給元素賦值np.where、np.clip問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06Python學(xué)習(xí)之a(chǎn)syncore模塊用法實例教程
這篇文章主要介紹了Python學(xué)習(xí)之a(chǎn)syncore模塊用法,主要講述了asyncore模塊的組成、原理及相關(guān)函數(shù)的用法,對于使用Python進行網(wǎng)絡(luò)編程來說非常實用,需要的朋友可以參考下2014-09-09