1.python数据与yaml数据切换
yaml文件中的数据读取出来,并转换为python数据
#读取yaml数据,将其转换为python数据,使用load函数
import yaml
withopen('data2.yaml','r') as f:
res= yaml.load(stream=f,Loader=yaml.FullLoader)
print(res)
python数据写入到yaml文件中
import yaml
#数据写入到yaml文件中,使用dump函数,将python数据转换为yaml数据,并保存在文件中
withopen('data3.yaml','w',encoding='utf-8') as f:
yaml.dump(cases,f,allow_unicode=True)#allow_unicode=True在数据中存在中文时,解决编码问题
2.python数据与json数据转换
python数据转换为json数据
import json
#python数据转换为json数据,使用dumps函数
li=[None,False,{'a':'python'}]
print(json.dumps(li))
json数据转换为python数据
import json
#json数据转换为python数据,使用loads函数
jstr='[null, false]'
print(json.loads(jstr))
将python数据,写入json文件
import json
#将python数据,写入json文件(自动化转换格式),使用dump函数
data=[None,True,{'a':'hello'}]
withopen(r'E:\Python\python 41\working\day16\testdata\hello.json','w',encoding='utf-8') as f:
json.dump(data,f)
加载json文件,转换为python对应的数据格式
import json
#加载json文件,转换为python对应的数据格式,使用load函数
withopen(r'E:\Python\python 41\working\day16\testdata\hello.json','r',encoding='utf-8') as f:
res=json.load(f)
print(res)