筆記||Python3進階之讀取和寫入yaml配置文件

yaml是專門用來寫配置文件的語言,簡潔強大,遠比JSON格式方便,yaml在python語言中有PyYAML安裝包。python

       - 首先須要pip安裝:pip install pyyamlandroid

       - yaml基本語法規則:大小寫敏感chrome

                                          使用縮進表示層級關係數組

                                          縮進時不容許Tab鍵,只容許使用空格app

                                          #  表示註釋ui

------------------------------------python代碼讀取yaml文件--------------------------------------code

      import  yamlorm

      import osip

      # 獲取當前腳本所在文件夾路徑utf-8

      curpath = os.path.dirname(os.path.realpath(__file__))

      # print(curpath)

      # 獲取yaml文件路徑

      yamlpath = os.path.join(curpath, "cfgyaml.yaml")

      # open方法打開文件直接讀出來

      f = open(yamlpath, 'r', encoding='utf-8')

      cfg = f.read()

      print(type(cfg))

      # print(cfg)

      # 用load方法轉字典

      d = yaml.load(cfg)

      print(type(d))

      print(d)

---------------------------------cfgyaml.yaml文件內容以下-------------------------------------- 

# yaml中的數組,至關於python中的列表

- admin1: 123456

- admin2: 234567

- admin3: 345678

# yaml中的鍵值對,至關於python中的字典

# test1: 

#     user: username

#     pw: 123456

---------------------------------------------------------------------------------------------------------------------------------------------------------

用yaml模塊寫入字典嵌套字典這種複雜的數據,會出現大括號{},不是真正的yaml文件數據,能夠用ruamel模塊解決。

安裝:pip install ruamel.yaml

使用方法跟yaml差很少,只是在使用dump方法多一個參數:Dumper=yaml.RoundTripDumper

---------------------------python代碼寫入yaml文件----------------------------------

import os

from ruamel import yaml

# 將字典寫入到yaml

desired_caps = {

                       'platformName': 'Android',

                       'platformVersion': '7.0',

                       'deviceName': 'ASRNW1111111111'

                       'appPackage': 'com.tencent.com',

                       'appActivity': 'ui.LauncherUI',

                       'automationName': 'Uiautomator2',

                       'unicodeKeyboard': True,

                       'resetKeyboard': True,

                       'noReset': True,

                       'chromeOptions': {'androidProcess': 'com.tencent.com'}

}

curpath = os.path.dirname(os.path.realpath(__file__))

yamlpath = os.path.join(curpath, "cfgyaml.yaml")

 

# 寫入到yaml文件

with open(yamlpath, 'w', encoding="utf-8") as f:

      yaml.dump(desired_caps, f, Dumper=yaml.RoundTripDumper)

--------------------------------------------------------------------------------------------------------------------

使用ruamel.yaml模塊也能讀yaml文件,使用方法相對以前的yaml.load方法多加了一個參數:Loader=yaml.Loader

如:

     rea = open(yamlpath, 'r')

     a = rea.load()

     b = yaml.load(a, Loader=yaml.Loader)

     print(b)

相關文章
相關標籤/搜索