Python讀寫yaml文件
1.關(guān)于yaml
yaml基本語法規(guī)則:
- 大小寫敏感
- 使用縮進(jìn)表示層級關(guān)系
- 縮進(jìn)時(shí)不允許使用
Tab鍵,只允許使用空格。 - 縮進(jìn)的空格數(shù)目不重要,只要相同層級的元素左側(cè)對齊即可
- #表示注釋,從這個字符一直到行尾,都會被解析器忽略,這個和
python的注釋一樣
2.yaml數(shù)據(jù)結(jié)構(gòu)
YAML 支持的數(shù)據(jù)結(jié)構(gòu)有三種:
- 對象
鍵值對的集合,又稱為映射(mapping)/ 哈希(hashes) / 字典(dictionary)
對象的一組鍵值對,使用冒號結(jié)構(gòu)表示。
- 數(shù)組
一組按次序排列的值,又稱為序列(sequence) / 列表(list)
一組連詞線開頭的行,構(gòu)成一個數(shù)組。
- 純量(
scalars)
單個的、不可再分的值
包括字符串,布爾值,整數(shù),浮點(diǎn)數(shù),Null,時(shí)間,日期
3.yaml文件格式
auth.login: ? data: ? ? name: '18888888883' ? ? password: jnyj123456 ? url: https://XXXX-api-XXXX.zje.com/auth/login headers: ? Accept: '*/*' ? Accept-Encoding: gzip, deflate, br ? Accept-Language: zh-CN,zh;q=0.9 ? Connection: keep-alive ? Content-Length: '46' ? Content-type: application/json ? Host: dexin-api-test.zje.com ? Origin: https://XXXX-spa-XXX.zje.com ? Referer: https://XXXX-spa-XXX.zje.com/ ? Sec-Fetch-Dest: empty ? Sec-Fetch-Mode: cors ? Sec-Fetch-Site: same-site ? User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, ? ? like Gecko) Chrome/98.0.4758.80 Safari/537.36 ? authorization: Bearer ? sec-ch-ua: '" Not A;Brand";v="33" ? sec-ch-ua-mobile: ?0000 ? sec-ch-ua-platform: macOSis
學(xué)習(xí)產(chǎn)出:
class OpenYaml(object):
? ? def __init__(self):
? ? ? ? self.file_path = os.path.join(route("/DataYaml/yaml.yaml")) ?# 拼接讀取的文件路徑
? ? def open(self, *args):
? ? ? ? '''
? ? ? ? ? ?args[0]: 字典名稱
? ? ? ? ? ?args[1]: 字段值
? ? ? ? ? ?讀取文件
? ? ? ? '''
? ? ? ? try:
? ? ? ? ? ? if len(args) == 2: ?# 根據(jù)傳值判斷執(zhí)行內(nèi)容
? ? ? ? ? ? ? ? with open(self.file_path, "r") as f: ?# 讀取yaml
? ? ? ? ? ? ? ? ? ? Json = f.read() ?# 獲取yaml
? ? ? ? ? ? ? ? ? ? Dict = yaml.safe_load(Json)[args[0]] ?# 提取制定內(nèi)容
? ? ? ? ? ? ? ? if args[1] in Dict.keys(): ?# 判斷key是否存在
? ? ? ? ? ? ? ? ? ? logs.info(f"yaml文件,查找內(nèi)容成功,內(nèi)容:{Dict[args[1]]}")
? ? ? ? ? ? ? ? ? ? return Dict[args[1]]
? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? print(f"對應(yīng)字段{args[1]}不存在...")
? ? ? ? ? ? ? ? ? ? logs.info(f"對應(yīng)字段{args[1]}不存在...")
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? with open(self.file_path, "r") as f:
? ? ? ? ? ? ? ? ? ? Json = f.read()
? ? ? ? ? ? ? ? ? ? Dict = yaml.safe_load(Json)[args[0]]
? ? ? ? ? ? ? ? return Dict
? ? ? ? except Exception as e:
? ? ? ? ? ? print(f'讀取yaml文件,報(bào)錯:{e}')
? ? ? ? ? ? logs.info(f'讀取yaml文件,報(bào)錯:{e}')
? ? def Wri_file(self, *args):
? ? ? ? '''
? ? ? ? :param args: args[0] 接口字段、args[1] key、 args[2] value
? ? ? ? :return: None
? ? ? ? 把字段寫入yaml
? ? ? ? '''
? ? ? ? try:
? ? ? ? ? ? with open(self.file_path, encoding="utf-8") as f: ?# 讀取文件
? ? ? ? ? ? ? ? data = yaml.load(f.read(), Loader=yaml.FullLoader) ?# 獲取讀取內(nèi)容
? ? ? ? ? ? print(data[args[0]])
? ? ? ? ? ? if data is not None: ?# 判斷讀取內(nèi)容是否為空
? ? ? ? ? ? ? ? if str(data[args[0]][args[1]]) in str(data[args[0]]): ?# 判斷name是否存在在dict
? ? ? ? ? ? ? ? ? ? data[args[0]][args[1]] = args[2]
? ? ? ? ? ? ? ? ? ? with open(self.file_path, 'w', encoding="utf-8") as f: ?# 寫入
? ? ? ? ? ? ? ? ? ? ? ? yaml.dump(data, stream=f, allow_unicode=True)
? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? print("寫入文件的字段不存在!寫入失敗...")
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? logs.info("寫入文件的返回值為空!不能寫入...")
? ? ? ? except Exception as y:
? ? ? ? ? ? logs.info(f"寫入文件失敗:{y}")
if __name__ == "__main__":
? ? OpenYaml().Wri_file("headers", "Content-Length", "22")
?? ?OpenYaml().open("auth.login", "data")到此這篇關(guān)于Python讀寫yaml文件的文章就介紹到這了,更多相關(guān)Python讀寫yaml內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python 函數(shù)中的內(nèi)置函數(shù)及用法詳解
這篇文章主要介紹了python 函數(shù)中的內(nèi)置函數(shù) 及用法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-07
2020新版本pycharm+anaconda+opencv+pyqt環(huán)境配置學(xué)習(xí)筆記,親測可用
這篇文章主要介紹了2020新版本pycharm+anaconda+opencv+pyqt環(huán)境配置學(xué)習(xí)筆記,親測可用,特此分享到腳本之家平臺,需要的朋友可以參考下2020-03-03
Python字典fromkeys()方法使用代碼實(shí)例
這篇文章主要介紹了Python字典fromkeys()方法使用代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
Python3使用Matplotlib 繪制精美的數(shù)學(xué)函數(shù)圖形
這篇文章主要介紹了Python3使用Matplotlib 繪制精美的數(shù)學(xué)函數(shù)圖形,非常不錯,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
python實(shí)現(xiàn)異常信息堆棧輸出到日志文件
今天小編就為大家分享一篇python實(shí)現(xiàn)異常信息堆棧輸出到日志文件,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python中的getter與setter及deleter使用示例講解
這篇文章主要介紹了Python中的getter與setter及deleter使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01

