一、python使用自帶的configparser模塊用來讀取配置文件,使用之前需要先導入該模塊。
基礎讀取配置文件
- -read(filename) 直接讀取文件內容
- -sections() 得到所有的section,並以列表的形式返回
- -options(section) 得到該section的所有option
- -items(section) 得到該section的所有鍵值對
- -get(section,option) 得到section中option的值,返回為string類型
- -getint(section,option) 得到section中option的值,返回為int類型,還有相應的getboolean()和getfloat() 函數
基礎寫入配置文件
write(fp) 將config對象寫入至某個 .ini 格式的文件 Write an .ini-format representation of the configuration state. add_section(section) 添加一個新的section
set( section, option, value 對section中的option進行設置,需要調用write將內容寫入配置文件
remove_section(section) 刪除某個 section
remove_option(section, option) 刪除某個 section 下的 option
1、先創建config.ini文件
2、創建一個readconfig.py文件,讀取配置文件信息
1 import configparser 2 from base.path import config_dir 3 4 class ReadConfig: 5 def __init__(self): 6 configpath = config_dir(fileName='case_data.ini') #配置文件的路徑 7 self.conf = configparser.RawConfigParser() 8 self.conf.read(configpath,encoding='utf-8') #讀取配置文件 9 10 def get_case_data(self,param): 11 '''返回配置文件中具體的信息''' 12 value = self.conf.get('test_data',param) #獲得具體的配置信息 13 return value 14 15 if __name__ == '__main__': 16 17 test = ReadConfig() 18 t = test.get_case_data("username") 19 print(t,type(t))
3、寫入配置文件
1 import configparser 2 import os 3 4 os.chdir("D:\\Python_config") 5 cf = configparser.ConfigParser() 6 7 # add section / set option & key 8 cf.add_section("test") 9 cf.set("test", "count", 1) 10 cf.add_section("test1") 11 cf.set("test1", "name", "aaa") 12 13 # write to file 14 with open("test2.ini","w+") as f: 15 cf.write(f)
4、修改配置文件中的內容,一定要read()
1 import configparser 2 import os 3 4 os.chdir("D:\\Python_config") 5 cf = configparser.ConfigParser() 6 7 # modify cf, be sure to read! 8 cf.read("test2.ini") 9 cf.set("test", "count", 2) # set to modify 10 cf.remove_option("test1", "name") 11 12 # write to file 13 with open("test2.ini","w+") as f: 14 cf.write(f)
二、YAML 是專門用來寫配置文件的語言,非常簡潔和強大,遠比 JSON 格式方便。YAML在python語言中有PyYAML安裝包。
1、首先需要安裝:pip install pyyaml
2、它的基本語法規則如下:
1、大小寫敏感
2、使用縮進表示層級關系
3、縮進時不允許使用Tab鍵,只允許使用空格。
4、縮進的空格數目不重要,只要相同層級的元素左側對齊即可
5、#
表示注釋,從這個字符一直到行尾,都會被解析器忽略,這個和python的注釋一樣
YAML 支持的數據結構有三種:
1、對象:鍵值對的集合,又稱為映射(mapping)/ 哈希(hashes) / 字典(dictionary)
2、數組:一組按次序排列的值,又稱為序列(sequence) / 列表(list)
3、純量(scalars):單個的、不可再分的值。字符串、布爾值、整數、浮點數、Null、時間、日期
3、具體實例:
(1)dict類型 key:value
1 appname: xxxxxxxx.apk 2 noReset: True 3 autoWebview: Ture 4 appPackage: xxxxxxxxx 5 appActivity: xxxxxxxxxxx 6 automationName: UiAutomator2 7 unicodeKeyboard: True # 是否使用unicodeKeyboard的編碼方式來發送字符串 8 resetKeyboard: True # 是否在測試結束后將鍵盤重設系統默認的輸入法 9 newCommandTimeout: 120
(2) dict套dict類型
1 info1: 2 user:admin 3 pwd:111111 4 5 info2: 6 user2:admin 7 pwd2:111111
(3)list類型 前面加上‘-’符號,且數字讀出來的是int 或者float
1 -admin: 111111
2 -host : 222222
(4) 純量 純量:最基本、不可再分的值。
1 1、數值直接以字面量的形式表示 2 number: 12.30 # {'number': 12.3} 3 4 2、布爾值用true和false表示 5 isSet: true # {'isSet': True} 6 isSet1: false # {'isSet1': False} 7 8 3、null用~表示 9 parent: ~ # {'parent': None} 10 11 4、時間采用 ISO8601 格式 12 time1: 2001-12-14t21:59:43.10-05:00 13 # {'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000)} 14 15 5、日期采用復合 iso8601 格式的年、月、日表示 16 date: 2017-07-31 17 # {'date': datetime.date(2017, 7, 31)} 18 19 6、YAML 允許使用兩個感嘆號,強制轉換數據類型 20 int_to_str: !!str 123 21 bool_to_str: !!str true # {'bool_to_str': 'true'}
(5)數組
1 1、數組可以采用行內表示法 2 animal: [Cat, Dog] 3 # 打印結果:{'animal': ['Cat', 'Dog']} 4 5 2、一組連詞線開頭的行,構成一個數組 6 animal1: - Cat - Dog - Goldfish 7 # 打印結果:{'animal1': ['Cat', 'Dog', 'Goldfish']}
(6)復合類型
list嵌套dict:
1 - user : admin 2 pwd : '123456' 3 - user : host 4 pwd : '111111'
其打印結果:
- dict 嵌套list:
group1: - admin - '123456' group2: - host - '1111111'
其打印結果:
(7)字符串
1 默認不使用引號表示,也可以用單引號和雙引號進行表示。 2 but雙引號不會對特殊轉義字符進行轉義。 3 單引號中若還有單引號,必須連續使用兩個單引號轉義 4 5 1、字符串默認不使用引號表示 6 str1: 這是一個字符串 7 8 2、如果字符串之中包含空格或特殊字符,需要放在引號之中。 9 str2: '內容:*字符串' 10 11 3、單引號和雙引號都可以使用,雙引號不會對特殊字符轉義。 12 str3: '內容\n字符串' 13 str4: "content\n string" 14 15 4、單引號之中如果還有單引號,必須連續使用兩個單引號轉義。 16 s3: 'labor''s day' 17 18 5、字符串可以寫成多行,從第二行開始,必須有一個單空格縮進。換行符會被轉為空格 19 strline: 這是一段 20 多行 21 字符串 22 23 6、多行字符串可以使用|保留換行符,也可以使用>折疊換行 24 this: | 25 Foo 26 Bar 27 that: > 28 Foo 29 Bar 30 31 7、+表示保留文字塊末尾的換行,-表示刪除字符串末尾的換行。 32 s4: | 33 Foo4 34 s5: |+ 35 Foo5 36 s6: |- 37 Foo6 38 s7: | 39 Foo7
(8)對象
1 1、對象的一組鍵值對,使用冒號結構表示。 2 animal: pets 3 # 打印結果:{'animal': 'pets'} 4 5 2、Yaml 也允許另一種寫法,將所有鍵值對寫成一個行內對象 6 dict1: { name: Steve, foo: bar } 7 # 打印結果:{'dict1': {'foo': 'bar', 'name': 'Steve'}}
4、Python代碼實現讀取yaml文件
1 import yaml 2 from base.public import yanml_dir 3 4 def appium_desired(): 5 ''' 6 啟動app 7 :return: driver 8 ''' 9 logging.info("============開始啟動app===========") 10 with open(yanml_dir('driver.yaml'),'r',encoding='utf-8') as file : #encoding='utf-8'解決文件中有中文時亂碼的問題 11 data = yaml.load(file) #讀取yaml文件 12 desired_caps = {} 13 desired_caps['platformName'] = data['platformName'] 14 desired_caps['deviceName'] = data['deviceName'] 15 desired_caps['platformVersion'] = data['platformVersion'] 16 desired_caps['appPackage'] = data['appPackage'] 17 desired_caps['appActivity'] = data['appActivity'] 18 desired_caps['noReset'] = data['noReset'] 19 desired_caps['automationName'] = data['automationName'] 20 desired_caps['unicodeKeyboard'] = data['unicodeKeyboard'] 21 desired_caps['resetKeyboard'] = data['resetKeyboard'] 22 desired_caps['newCommandTimeout'] = data['newCommandTimeout'] 23 driver = webdriver.Remote('http://'+str(data['ip'])+':'+str(data['port'])+'/wd/hub',desired_caps) 24 logging.info("===========app啟動成功=============") 25 driver.implicitly_wait(5) 26 return driver
5、Python代碼實現寫入yaml文件
1 import yaml 2 from base.path import config_dir 3 yamlPath = config_dir(fileName='config.yaml') 4 5 def setYaml(): 6 '''寫入yaml文件中,a 追加寫入,w 覆蓋寫入''' 7 data = { 8 "cookie1": {'domain': '.yiyao.cc', 'expiry': 1521558688.480118, 'httpOnly': False, 'name': '_ui_', 'path': '/', 9 'secure': False, 'value': 'HSX9fJjjCIImOJoPUkv/QA=='}} 10 with open(yamlPath,'a',encoding='utf-8') as fw: 11 yaml.dump(data,fw) 12 13 if __name__ == '__main__': 14 setYaml()