接口測試中躺屁,需要把數(shù)據(jù)寫入文件试吁,再讀取文件數(shù)據(jù)。大多數(shù)的文件寫入都要求參數(shù)類型為字符型。比如txt,csv,xlsx
不少同學熄捍,寫入文件時看到報錯信息烛恤,直接使用字符型強制轉換,直接寫入文件余耽。
dict = {"a": "b","c": "d"}
str_dict =str(dict)
file_name = DATA_DIR+"/demo.txt"
with open(file_name,"w",encoding="utf-8") as f:
f.write(str_dict)
f.close()
終于闖關成功缚柏,把數(shù)據(jù)寫入了文件,到了讀取數(shù)據(jù)的時候了
with open(file_name,"r",encoding="utf-8") as f:
file_context = f.read()
print(file_context)
f.close()
print(file_context,type(file_context))
=>{'a': 'b', 'c': 'd'} <class 'str'>
讀數(shù)據(jù)好像也沒有什么問題碟贾,數(shù)據(jù)終于等到了高光時候币喧。使用數(shù)據(jù)傳入接口參數(shù)的時候,自己挖的坑還是得自己來填呀袱耽。杀餐。
#轉換成python對象dict型
import json
json.loads(file_context)
=>以下是報錯信息
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "D:\Program Files\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "D:\Program Files\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\Program Files\Python37\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
錯誤原因: 這個錯誤是由于json.loads()接受的參數(shù)不是json定義的標準格式。key值不是使用的雙引號朱巨,而是單引號J非獭!<叫琼讽!
json遵循“key-value”的這樣一種方式。比如:{"name" : "zhuxiao5"}洪唐。Json的key需要嚴格使用雙引號钻蹬;但是python 字典型dict,key使用單引號/雙引號都可以
dict = {"a": "b","c": "d"}
dict1 = {'a':'b'}
type(dict) => <class 'dict'>
type(dict1) => <class 'dict'>
假如你也遇到了以上的問題凭需,那下面的內容應該可以幫到你问欠。
Json簡介
Json(JavaScript Object Notation)
很多網站都會用到Json格式來進行數(shù)據(jù)的傳輸和交換。
這因為Json是一種輕量級的數(shù)據(jù)交換格式粒蜈,具有數(shù)據(jù)格式簡單顺献,讀寫方便易懂等很多優(yōu)點。用它來進行前后端的數(shù)據(jù)傳輸薪伏,大大的簡化了服務器和客戶端的開發(fā)工作量。
以下是避坑的兩個解決方案:
【方法一】數(shù)據(jù)寫入文件時粗仓,不直接使用str,強制轉換成字符型存入文件嫁怀,使用json.dumps()
#寫入文件
import json
from Common.project_path import *
dict = {"a": "b","c": "d"}
str_dict =str_dict =json.dumps(dict)
file_name = DATA_DIR+"/demo.txt"
with open(file_name,"w",encoding="utf-8") as f:
f.write(str_dict)
f.close()
#讀取文件,json.loads()格式轉換為python對象
with open(file_name,"r",encoding="utf-8") as f:
file_context = f.read()
print(file_context)
f.close()
print(file_context,type(file_context))
=>{"a": "b", "c": "d"} <class 'str'>
json.loads(file_context)
=>{'a': 'b', 'c': 'd'}
【方法二】數(shù)據(jù)寫入文件時借浊,直接存儲成json文件塘淑,使用json.dump(),json.load()轉換數(shù)據(jù)格式
#python對象,直接存入文件
import json
from Common.project_path import *
dict = {"a": "b","c": "d"}
file_name = DATA_DIR+"/demo.json"
with open(file_name,"w",encoding="utf-8") as f:
json.dump(dict,f)
f.close()
#直接讀取json文件數(shù)據(jù)
with open(file_name,"r",encoding="utf-8") as f:
data = json.load(f)
print(data,type(data))
f.close()
=>{'a': 'b', 'c': 'd'} <class 'dict'>