Python對yaml和json文件的讀取:
yaml文件讀取:
首先創建一個yaml文件test.yaml
import yaml #引入包
f=open(path) #建立Python的文件對象f, 打開yaml文件到文件對象f;注:這一操作在打開所有第三方文件格式的時候都要做,不一定是yaml文件
test=yaml.load(f) #通過yaml模塊中的load函數,將yaml 數據以Python中字典的形式加載進來
注:path是test.yaml的文件路徑,可以通過 path= os.path.dirname(os.path.realpath(_file_))+"test.yaml"的方式獲取,如果py文件和yaml文件在同一個文件夾下,可以直接用'test.yaml'
然后字典test中的數據就可以靈活運用了
json文件讀取:
json文件的讀取方式和處理方式和yaml文件相同
import json
f=open(path)
test=json.load(f)
一個簡單栗子:
# coding: UTF-8 import yaml import json f= open('test.yaml') test_f=yaml.load(f) print f print test_f g=open('test.json') test_g=json.load(g) print g print test_g print type(test_f) print type(test_g)
輸出
<open file 'test.yaml', mode 'r' at 0x100c2b810> {'Content-Type': 'application/x-www-form-urlencoded'} <open file 'test.json', mode 'r' at 0x100c2b8a0> {u'Content-Type': u'application/x-www-form-urlencoded'} <type 'dict'> <type 'dict'>
從以上的小栗子可以看出,yaml 文件和json文件的格式輸出雖然都是字典,但還是有小區別的,這就帶來一些影響
json的輸出帶u:也就是unicode的格式標志,而Python的格式一般會在文件開頭定義成UTF-8
這就導致對於json文件,解析時有時會出現錯誤,而接口測試的接口響應數據就是json格式,所以在出來接口響應數據的py文件中,要加入以下兩句:
import sys #設置默認解碼格式,如果不加這句請求的返回值有的是Unicode,logging輸出時會報解碼錯誤 reload(sys) sys.setdefaultencoding('utf-8')
而yaml 文件一般用做用例,來記錄請求參數
yaml文件與json文件的區別
yaml文件書寫格式:
Testcase_name:test Method: POST Testcase: - ID: 1 Header: Content-Type: application/x-www-form-urlencoded x-access-token: "" Data: name: "aa" age:"bb" Result: resultcode: 0 resultmsg: ""
yaml輸出格式:
{ 'Method': 'POST', 'Testcase_name': 'test' 'Testcase': [ {'Header': {'x-access-token': '', 'Content-Type': 'application/x-www-form-urlencoded'}, 'Data': {'age': 'bb', 'name': 'aa'}, 'ID': 1, 'Result': {'resultcode': 0, 'resultmsg': ''} } ], }
json文件書寫格式:
{ "Content-Type": "application/x-www-form-urlencoded" }
補充:python文件有自帶的讀取函數
讀取方式:
f=open('test_try.yaml') test=f.read()
這種方式不用引用模塊,但是test的類型是字符串