Yaml读写文件处理方式
一、格式
安装pyYaml包
yaml主要有三种类型的数据原语:Maps,Lists,Scales(按照官方法表达:“mappings (hashes/dictionaries), sequences (arrays/lists) and scalars (strings/numbers)”),基于这三种数据原语可以组合出任何数据结构。
- 破折号和空格( “
-” ):Lists集合 - 冒号和空格( “
:” ) :Maps键值对 - 井号( “
#” ):注释 - 三个破折号( “
---” ):文档内容分隔线(多用于文档开始的地方) - 三个冒号( “
...” ):表示文档的结束 - 锚点(“
&”),重复项抛锚(“*”):两者成对表达,像定义变量a,再引用变量a的关系,是一种重复项的替换。
yaml基于缩进的作用域跟python语法格式比较相似,缩进块方便数据的结构化。
注意:yaml文件大小写敏感,不允许使用用tab制表符号代替空格。
1.列表
- a - b
['a', 'b']
2.字典
boss: appActivity: .module.launcher.WelcomeActivity appPackage: com.hpbr.bosszhipin automationName: UiAutomator2 deviceName: ZXB newCommandTimeout: 6000 noReset: true platformName: Android plathformVersion: '10'
{'boss': {'appActivity': '.module.launcher.WelcomeActivity', 'appPackage': 'com.hpbr.bosszhipin', 'automationName': 'UiAutomator2', 'deviceName': 'ZXB', 'newCommandTimeout': 6000, 'noReset': True, 'platformName': 'Android', 'plathformVersion': '10'}}
安装yaml包
1.yaml文件的读取
def get_Yaml_boss_data(fileName): ''' 获取单个yaml文件页面数据 :param fileDir: 文件路径 :return:页面数据 ''' #打开yaml文件 fileDir= os.path.dirname(os.path.dirname(__file__))+f'/appium_basicCode/my_appium_code/boss/boss_data/{fileName}' fo = open(fileDir, 'r', encoding='utf-8') #使用第三方库去读取数据 # res = yaml.loads(fo,loader=yaml.FullLoader) #处理警告 res = yaml.load(fo,Loader = yaml.FullLoader) return res
2.yaml文件写入:写入也可以追加写入 "a",你懂的
def writ_yaml_data(fileName,data): ''' yaml里面写入内容 :param fileName:文件名 :param data:需要写入的数据 :return: ''' fileDir= os.path.dirname(os.path.dirname(__file__))+f'/appium_basicCode/my_appium_code/boss/boss_data/{fileName}' fo = open(fileDir, 'w', encoding='utf-8') #使用第三方库去读取数据 res = yaml.dump(data,fo) return res
3.yaml文件的读写
boss_desired_capabilities = {'boss':{
'platformName': 'Android',
'plathformVersion': '10',
'deviceName': 'zhuxibo',
'appPackage': 'com.hpbr.bosszhipin',
'appActivity': '.module.launcher.WelcomeActivity',
'noReset': True,
'newCommandTimeout': 6000,
'automationName': 'UiAutomator2', # 或者UiAutomator1
# 跳过UI2的安装,如果第一次运行程序,不要添加该配置
# 'skipServerInstallation':True
}}
#写入数据
writ_yaml_data('boss_para_data.yaml',boss_desired_capabilities)
res = get_Yaml_boss_data('boss_para_data.yaml')
print(res)
#修改需要修改的数据
res['boss']['deviceName']='ZXB'
#再将数据写入
res1= writ_yaml_data('boss_para_data.yaml',res)
print(res1)

浙公网安备 33010602011771号