Python 读取配置ini文件和yaml文件

1、python使用自带的configparser模块用来读取配置文件,使用以前须要先导入该模块。 python

基础读取配置文件

  • -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)                                    添加一个新的sectionweb

set( section, option, value                      对section中的option进行设置,须要调用write将内容写入配置文件
数组

remove_section(section)                             删除某个 sectioncookie

remove_option(section, option)                 删除某个 section 下的 option数据结构

一、先建立config.ini文件app

  

二、建立一个readconfig.py文件,读取配置文件信息dom

 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))

 三、写入配置文件函数

 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)

四、修改配置文件中的内容,必定要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)

 

2、YAML 是专门用来写配置文件的语言,很是简洁和强大,远比 JSON 格式方便。YAML在python语言中有PyYAML安装包。ui

  一、首先须要安装:pip  install pyyaml

  二、它的基本语法规则以下

    一、大小写敏感

    二、使用缩进表示层级关系

    三、缩进时不容许使用Tab键,只容许使用空格。

    四、缩进的空格数目不重要,只要相同层级的元素左侧对齐便可

    五、# 表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释同样

    YAML 支持的数据结构有三种:

    一、对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)

    二、数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)

    三、纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期

  三、具体实例:   

  (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 三、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'

其打印结果:
image.png

  • dict 嵌套list:
group1:
    - admin
    - '123456'
group2:
    - host 
    - '1111111'

其打印结果:
image.png

  (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 六、多行字符串能够使用|保留换行符,也能够使用>折叠换行
24 this: |
25   Foo
26   Bar
27 that: >
28   Foo
29   Bar
30   
31 七、+表示保留文字块末尾的换行,-表示删除字符串末尾的换行。
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'}}

  四、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

  五、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()
相关文章
相关标签/搜索